当前位置: 首页>>代码示例>>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;未经允许,请勿转载。