當前位置: 首頁>>代碼示例>>Python>>正文


Python cElementTree.ParseError方法代碼示例

本文整理匯總了Python中xml.etree.cElementTree.ParseError方法的典型用法代碼示例。如果您正苦於以下問題:Python cElementTree.ParseError方法的具體用法?Python cElementTree.ParseError怎麽用?Python cElementTree.ParseError使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在xml.etree.cElementTree的用法示例。


在下文中一共展示了cElementTree.ParseError方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: isxmlorjson

# 需要導入模塊: from xml.etree import cElementTree [as 別名]
# 或者: from xml.etree.cElementTree import ParseError [as 別名]
def isxmlorjson(s):
    try:
        json.loads(s)
        isjson = True
    except ValueError:
        isjson = False

    try:
        ETree.ElementTree(ETree.fromstring(s))
        isxml = True
    except ETree.ParseError:
        isxml = False

    if isjson and isxml:
        raise ValueError('This file appears to be both XML and JSON. I am ' +
                         'confused. Goodbye')

    if isjson:
        return 'json'
    elif isxml:
        return 'xml'
    else:
        return None 
開發者ID:datacenter,項目名稱:arya,代碼行數:25,代碼來源:arya.py

示例2: parseWindowsAliases

# 需要導入模塊: from xml.etree import cElementTree [as 別名]
# 或者: from xml.etree.cElementTree import ParseError [as 別名]
def parseWindowsAliases(self, aliases):

        try:
            with open(aliases) as xmlfile:
                xmlroot = XML.ElementTree(file=xmlfile).getroot()
        except (IOError, XMLParseError):
            raise ValueError("Unable to open or read windows alias file: {}".format(aliases))

        # Extract the mappings
        try:
            for elem in xmlroot.findall("./windowsZones/mapTimezones/mapZone"):
                if elem.get("territory", "") == "001":
                    if elem.get("other") not in self.links:
                        self.links[elem.get("other")] = elem.get("type")
                    else:
                        print("Ignoring duplicate Windows alias: {}".format(elem.get("other")))
        except (ValueError, KeyError):
            raise ValueError("Unable to parse windows alias file: {}".format(aliases)) 
開發者ID:apple,項目名稱:ccs-pycalendar,代碼行數:20,代碼來源:tzconvert.py

示例3: __get_packages

# 需要導入模塊: from xml.etree import cElementTree [as 別名]
# 或者: from xml.etree.cElementTree import ParseError [as 別名]
def __get_packages(xml):
        root = ElTr.fromstring(xml.replace('\n', ' '))
        packages = root[0].findall("{urn:dvb:ipisdns:2006}Package")
        package_list = {}
        for package in packages:
            package_name = 'unknown'
            try:
                package_name = package[0].text
                package_list[package_name] = {
                    'id': package.attrib['Id'],
                    'name': package_name,
                    'services': {}}
                for service in package:
                    if not service.tag == '{urn:dvb:ipisdns:2006}PackageName':
                        service_id = service[0].attrib['ServiceName']
                        package_list[package_name]['services'][service_id] = service[1].text
            except (KeyError, ElTr.ParseError) as ex:
                logger.error('El paquete %s no tiene la estructura correcta: %s' % (package_name, str(ex.args)))
        logger.info('Paquetes: %i' % len(package_list))
        return package_list 
開發者ID:MovistarTV,項目名稱:tv_grab_es_movistartv,代碼行數:22,代碼來源:tv_grab_es_movistartv.py

示例4: get_snap_list

# 需要導入模塊: from xml.etree import cElementTree [as 別名]
# 或者: from xml.etree.cElementTree import ParseError [as 別名]
def get_snap_list(mnode, volname=""):
    """Parse the output of 'gluster snapshot list' command.
    If a volname is provided then the output will be specific
    to that volume.

    Args:
        mnode (str): Node on which command has to be executed.

    Kwargs:
        volname (str): volume name

    Returns:
        NoneType: None if command execution fails, parse errors.
        list: list of snapshots on success.

    Examples:
        >>> get_snap_list('abc.lab.eng.xyz.com')
        ['snap1', 'snap2']
    """

    cmd = "gluster snapshot list %s --xml" % volname
    ret, out, _ = g.run(mnode, cmd)
    if ret != 0:
        g.log.error("Failed to execute 'snapshot list' on node %s. "
                    "Hence failed to get the snapshot list.", mnode)
        return None

    try:
        root = etree.XML(out)
    except etree.ParseError:
        g.log.error("Failed to parse the gluster snapshot "
                    "list xml output.")
        return None

    snap_list = []
    for snap in root.findall("snapList/snapshot"):
        snap_list.append(snap.text)

    return snap_list 
開發者ID:gluster,項目名稱:glusto-tests,代碼行數:41,代碼來源:snap_ops.py

示例5: tier_detach_start_and_get_taskid

# 需要導入模塊: from xml.etree import cElementTree [as 別名]
# 或者: from xml.etree.cElementTree import ParseError [as 別名]
def tier_detach_start_and_get_taskid(mnode, volname):
    """Parse the output of 'gluster volume tier detach start' command.

    Args:
        mnode (str): Node on which command has to be executed.
        volname (str): volume name

    Returns:
        NoneType: None if command execution fails, parse errors.
        dict: dict on success.

    Examples:
        >>> tier_detach_start_and_get_taskid('abc.lab.eng.xyz.com',
                                             "testvol")
        {'task-id': '8020835c-ff0d-4ea1-9f07-62dd067e92d4'}
    """

    cmd = "gluster volume tier %s detach start --xml" % volname
    ret, out, _ = g.run(mnode, cmd)
    if ret != 0:
        g.log.error("Failed to execute 'detach tier start' on node %s. "
                    "Hence failed to parse the detach tier start.", mnode)
        return None

    try:
        root = etree.XML(out)
    except etree.ParseError:
        g.log.error("Failed to parse the gluster detach tier "
                    "start xml output.")
        return None

    tier_status = {}
    for info in root.findall("volDetachTier"):
        for element in info.getchildren():
            tier_status[element.tag] = element.text
    return tier_status 
開發者ID:gluster,項目名稱:glusto-tests,代碼行數:38,代碼來源:tiering_ops.py

示例6: is_heal_disabled

# 需要導入模塊: from xml.etree import cElementTree [as 別名]
# 或者: from xml.etree.cElementTree import ParseError [as 別名]
def is_heal_disabled(mnode, volname):
    """Check if heal is disabled for a volume.

    Args:
        mnode : Node on which commands are executed
        volname : Name of the volume

    Returns:
        bool : True if heal is disabled on volume. False otherwise.
        NoneType: None if unable to get the volume status shd or parse error.
    """
    cmd = "gluster volume status %s shd --xml" % volname
    ret, out, _ = g.run(mnode, cmd, log_level='DEBUG')
    if ret != 0:
        g.log.error("Failed to get the self-heal-daemon status for the "
                    "volume" % volname)
        return None

    try:
        root = etree.XML(out)
    except etree.ParseError:
        g.log.error("Failed to parse the volume status shd xml output.")
        return None

    operr = root.find("opErrstr")
    if operr:
        if "Self-heal Daemon is disabled for volume" in operr.text:
            return True
    return False 
開發者ID:gluster,項目名稱:glusto-tests,代碼行數:31,代碼來源:heal_libs.py

示例7: _poll

# 需要導入模塊: from xml.etree import cElementTree [as 別名]
# 或者: from xml.etree.cElementTree import ParseError [as 別名]
def _poll(self, url):
        request = urllib2.Request(url)
        for key, value in self.http_headers:
            request.add_header(key, value)

        try:
            self.log.info('Downloading feed from: "%s"', url)
            _, fileobj = yield utils.fetch_url(request)
        except utils.FetchUrlFailed as e:
            self.log.error('Failed to download feed "%s": %r', url, e)
            idiokit.stop(False)

        self.log.info("Finished downloading the feed.")

        byte = fileobj.read(1)
        while byte and byte != "<":
            byte = fileobj.read(1)

        if byte == "<":
            fileobj.seek(-1, 1)
            try:
                for _, elem in etree.iterparse(fileobj):
                    for event in self._parse(elem, url):
                        if event:
                            yield idiokit.send(event)
            except ParseError as e:
                self.log.error('Invalid format on feed: "%s", "%r"', url, e) 
開發者ID:abusesa,項目名稱:abusehelper,代碼行數:29,代碼來源:rssbot.py

示例8: load_annotations

# 需要導入模塊: from xml.etree import cElementTree [as 別名]
# 或者: from xml.etree.cElementTree import ParseError [as 別名]
def load_annotations(self, image_index):
        filename = self.image_names[image_index] + '.xml'
        try:
            tree = ET.parse(os.path.join(self.data_dir, 'Annotations', filename))
            return self.__parse_annotations(tree.getroot())
        except ET.ParseError as e:
            raise_from(ValueError('invalid annotations file: {}: {}'.format(filename, e)), None)
        except ValueError as e:
            raise_from(ValueError('invalid annotations file: {}: {}'.format(filename, e)), None) 
開發者ID:OlafenwaMoses,項目名稱:ImageAI,代碼行數:11,代碼來源:pascal_voc.py

示例9: load_annotations

# 需要導入模塊: from xml.etree import cElementTree [as 別名]
# 或者: from xml.etree.cElementTree import ParseError [as 別名]
def load_annotations(self, image_index):
        """ Load annotations for an image_index.
        """
        filename = self.image_names[image_index] + '.xml'
        try:
            tree = ET.parse(os.path.join(self.data_dir, 'Annotations', filename))
            return self.__parse_annotations(tree.getroot())
        except ET.ParseError as e:
            raise_from(ValueError('invalid annotations file: {}: {}'.format(filename, e)), None)
        except ValueError as e:
            raise_from(ValueError('invalid annotations file: {}: {}'.format(filename, e)), None) 
開發者ID:weecology,項目名稱:DeepForest,代碼行數:13,代碼來源:pascal_voc.py

示例10: _translateExceptions

# 需要導入模塊: from xml.etree import cElementTree [as 別名]
# 或者: from xml.etree.cElementTree import ParseError [as 別名]
def _translateExceptions(original):
    try:
        yield None
    except ExpatError as e:
        raise XMLSyntaxError(original, e.args[0], e.lineno)
    except (cet.ParseError, et.ParseError) as e:
        raise XMLSyntaxError(original, e.args[0], e.lineno) 
開發者ID:IBM,項目名稱:pyxcli,代碼行數:9,代碼來源:xml_util.py

示例11: parse

# 需要導入模塊: from xml.etree import cElementTree [as 別名]
# 或者: from xml.etree.cElementTree import ParseError [as 別名]
def parse(self):
        try:
            tree = ET.parse(self.output)
        except ET.ParseError as e:
            return
        except Exception as e:
            raise e
        '''
        if self.output.startswith('.tmp-nmap'):
            os.remove(self.output)
        '''
        root = tree.getroot()
        result = {}
        filter_flag = True
        for host in root.findall('host'):
            ip = host.find('address').get('addr')
            result[ip] = {}
            for port in host.find('ports').findall('port'):
                if port.find('state').get('state') not in ('filtered', 'closed'):
                    filter_flag = False
                if port.find('state').get('state') == 'open':
                    service = port.find('service')
                    if service is None:
                        continue
                    service = service.attrib
                    if service['name'] == 'tcpwrapped':
                        continue
                    service.pop('conf')
                    service.pop('method')
                    result[ip][port.get('portid')] = service
            if result[ip] == {}:
                del result[ip]
        if not result:
            if filter_flag:
                print('All open ports detected by nmap are actually filtered or closed!')
            else:
                print('Failed to parse nmap xml!')
            return None
        self.result = result
        return result 
開發者ID:LyleMi,項目名稱:Saker,代碼行數:42,代碼來源:nmap.py

示例12: pmcxml2bioc

# 需要導入模塊: from xml.etree import cElementTree [as 別名]
# 或者: from xml.etree.cElementTree import ParseError [as 別名]
def pmcxml2bioc(pmcxmlFilename, biocFilename):
	try:
		with bioc.BioCXMLDocumentWriter(biocFilename) as writer:
			for pmcDoc in processPMCFile(pmcxmlFilename):
				biocDoc = bioc.BioCDocument()
				biocDoc.id = pmcDoc["pmid"]
				biocDoc.infons['title'] = " ".join(pmcDoc["textSources"]["title"])
				biocDoc.infons['pmid'] = pmcDoc["pmid"]
				biocDoc.infons['pmcid'] = pmcDoc["pmcid"]
				biocDoc.infons['doi'] = pmcDoc["doi"]
				biocDoc.infons['year'] = pmcDoc["pubYear"]
				biocDoc.infons['month'] = pmcDoc["pubMonth"]
				biocDoc.infons['day'] = pmcDoc["pubDay"]
				biocDoc.infons['journal'] = pmcDoc["journal"]
				biocDoc.infons['journalISO'] = pmcDoc["journalISO"]

				offset = 0
				for groupName,textSourceGroup in pmcDoc["textSources"].items():
					subsection = None
					for textSource in textSourceGroup:
						textSource = trimSentenceLengths(textSource)
						passage = bioc.BioCPassage()

						subsectionCheck = textSource.lower().strip('01234567890. ')
						if subsectionCheck in allowedSubsections:
							subsection = subsectionCheck

						passage.infons['section'] = groupName
						passage.infons['subsection'] = subsection
						passage.text = textSource
						passage.offset = offset
						offset += len(textSource)
						biocDoc.add_passage(passage)

				writer.write_document(biocDoc)
	except etree.ParseError:
		raise RuntimeError("Parsing error in PMC xml file: %s" % pmcxmlFilename) 
開發者ID:jakelever,項目名稱:pubrunner,代碼行數:39,代碼來源:convert.py

示例13: validate_svg_file

# 需要導入模塊: from xml.etree import cElementTree [as 別名]
# 或者: from xml.etree.cElementTree import ParseError [as 別名]
def validate_svg_file(f):
    tag = None
    f.seek(0)
    try:
        for event, el in xml_et.iterparse(f, ('start',)):
            tag = el.tag
            break
    except xml_et.ParseError:
        pass

    if tag != '{http://www.w3.org/2000/svg}svg':
        raise ValidationError('Uploaded file is not an image or SVG file')

    f.seek(0)
    return f 
開發者ID:dvhb,項目名稱:dvhb-hybrid,代碼行數:17,代碼來源:utils.py

示例14: check_svg

# 需要導入模塊: from xml.etree import cElementTree [as 別名]
# 或者: from xml.etree.cElementTree import ParseError [as 別名]
def check_svg(path):
    tag = None
    fileptr = get_fileptr(path)
    try:
        for event, el in cElementTree.iterparse(fileptr, ('start',)):
            tag = el.tag
            break
    except cElementTree.ParseError:
        pass
    finally:
        fileptr.close()
    return tag == '{http://www.w3.org/2000/svg}svg' or tag == 'svg' 
開發者ID:sk1project,項目名稱:uniconvertor,代碼行數:14,代碼來源:__init__.py

示例15: parse_new_asx

# 需要導入模塊: from xml.etree import cElementTree [as 別名]
# 或者: from xml.etree.cElementTree import ParseError [as 別名]
def parse_new_asx(data):
    # Copied from mopidy.audio.playlists
    try:
        for _, element in elementtree.iterparse(data):
            element.tag = element.tag.lower()  # normalize
            for ref in element.findall('entry/ref[@href]'):
                yield fix_asf_uri(ref.get('href', '').strip())

            for entry in element.findall('entry[@href]'):
                yield fix_asf_uri(entry.get('href', '').strip())
    except elementtree.ParseError:
        return 
開發者ID:alexa-pi,項目名稱:AlexaPi,代碼行數:14,代碼來源:tunein.py


注:本文中的xml.etree.cElementTree.ParseError方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。