python类ParseError()的实例源码

binding.py 文件源码 项目:TA-statemachine 作者: doksu 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def __init__(self, response, _message=None):
        status = response.status
        reason = response.reason
        body = response.body.read()
        try:
            detail = XML(body).findtext("./messages/msg")
        except ParseError as err:
            detail = body
        message = "HTTP %d %s%s" % (
            status, reason, "" if detail is None else " -- %s" % detail)
        Exception.__init__(self, _message or message)
        self.status = status
        self.reason = reason
        self.headers = response.headers
        self.body = body
        self._response = response
cc_device_finder.py 文件源码 项目:CodeLabs 作者: TheIoTLearningInitiative 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def get_device_name(ip_addr):
    """ get the device friendly name for an IP address """

    try:
        conn = httplib.HTTPConnection(ip_addr + ":8008")
        conn.request("GET", "/ssdp/device-desc.xml")
        resp = conn.getresponse()

        if resp.status == 200:
            status_doc = resp.read()
            try:
                xml = ElementTree.fromstring(status_doc)

                device_element = xml.find("{urn:schemas-upnp-org:device-1-0}" + "device")

                return device_element.find("{urn:schemas-upnp-org:device-1-0}" + "friendlyName").text

            except ElementTree.ParseError:
                return ""    
        else:
            return "" 
    except:
        # unable to get a name - this might be for many reasons 
        # e.g. a non chromecast device on the network that responded to the search
        return ""
test_xml_etree.py 文件源码 项目:pefile.pypy 作者: cloudtracer 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def check_encoding(encoding):
    """
    >>> check_encoding("ascii")
    >>> check_encoding("us-ascii")
    >>> check_encoding("iso-8859-1")
    >>> check_encoding("iso-8859-15")
    >>> check_encoding("cp437")
    >>> check_encoding("mac-roman")
    >>> check_encoding("gbk")
    Traceback (most recent call last):
    ValueError: multi-byte encodings are not supported
    >>> check_encoding("cp037")
    Traceback (most recent call last):
    ParseError: unknown encoding: line 1, column 30
    """
    ET.XML("<?xml version='1.0' encoding='%s'?><xml />" % encoding)
test_xml_etree.py 文件源码 项目:pefile.pypy 作者: cloudtracer 项目源码 文件源码 阅读 17 收藏 0 点赞 0 评论 0
def error(xml):
    """

    Test error handling.

    >>> issubclass(ET.ParseError, SyntaxError)
    True
    >>> error("foo").position
    (1, 0)
    >>> error("<tag>&foo;</tag>").position
    (1, 5)
    >>> error("foobar<").position
    (1, 6)

    """
    try:
        ET.XML(xml)
    except ET.ParseError:
        return sys.exc_value
grasp.py 文件源码 项目:grasp 作者: textgain 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def feed(url, delay=1, cached=False, headers={'User-Agent': 'Grasp.py'}):
    s = download(url, headers=headers, delay=delay, cached=cached)
    for f in (rss, atom):
        try:
            for r in f(s):
                yield r
        except ElementTree.ParseError as e: # HTML?
            pass
        except:
            pass

# for story in feed('http://feeds.washingtonpost.com/rss/world'):
#     print(story)

#---- MAIL ----------------------------------------------------------------------------------------
# The mail() function sends a HTML-formatted e-mail from a Gmail account.
test_xml_etree.py 文件源码 项目:ndk-python 作者: gittor 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def error(xml):
    """

    Test error handling.

    >>> issubclass(ET.ParseError, SyntaxError)
    True
    >>> error("foo").position
    (1, 0)
    >>> error("<tag>&foo;</tag>").position
    (1, 5)
    >>> error("foobar<").position
    (1, 6)

    """
    try:
        ET.XML(xml)
    except ET.ParseError:
        return sys.exc_value
xml_tree_widget.py 文件源码 项目:gml_application_schema_toolbox 作者: BRGM 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def onResolveEmbedded(self):
        item = self.currentItem()
        QApplication.setOverrideCursor(Qt.WaitCursor)
        uri = item.data(1, Qt.UserRole)
        try:
            f = remote_open_from_qgis(uri)
            try:
                doc, ns_map = xml_parse(f)
            except ET.ParseError:
                # probably not an XML
                QApplication.restoreOverrideCursor()
                QMessageBox.warning(self, "XML parsing error", "The external resource is not a well formed XML")
                return

            ns_imap = {}
            for k, v in ns_map.items():
                ns_imap[v] = k
            fill_tree_with_element(self, item.parent(), doc.getroot(), ns_imap, get_custom_viewers(), ns_map)
        except RuntimeError as e:
            QApplication.restoreOverrideCursor()
            QMessageBox.warning(self, "Network error", e.args[0])
            return
        finally:
            QApplication.restoreOverrideCursor()
backends_xml_parser.py 文件源码 项目:Deploy_XXNET_Server 作者: jzp820927 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def ProcessXml(self, xml_str):
    """Parses XML string and returns object representation of relevant info.

    Args:
      xml_str: The XML string.
    Returns:
      A list of Backend object containg information about backends from the XML.
    Raises:
      AppEngineConfigException: In case of malformed XML or illegal inputs.
    """
    try:
      self.backends = []
      self.errors = []
      xml_root = ElementTree.fromstring(xml_str)

      for child in xml_root.getchildren():
        self.ProcessBackendNode(child)

      if self.errors:
        raise AppEngineConfigException('\n'.join(self.errors))

      return self.backends
    except ElementTree.ParseError:
      raise AppEngineConfigException('Bad input -- not valid XML')
binding.py 文件源码 项目:mysplunk_csc 作者: patel-bhavin 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def __init__(self, response, _message=None):
        status = response.status
        reason = response.reason
        body = response.body.read()
        try:
            detail = XML(body).findtext("./messages/msg")
        except ParseError as err:
            detail = body
        message = "HTTP %d %s%s" % (
            status, reason, "" if detail is None else " -- %s" % detail)
        Exception.__init__(self, _message or message)
        self.status = status
        self.reason = reason
        self.headers = response.headers
        self.body = body
        self._response = response
backends_xml_parser.py 文件源码 项目:Docker-XX-Net 作者: kuanghy 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def ProcessXml(self, xml_str):
    """Parses XML string and returns object representation of relevant info.

    Args:
      xml_str: The XML string.
    Returns:
      A list of Backend object containg information about backends from the XML.
    Raises:
      AppEngineConfigException: In case of malformed XML or illegal inputs.
    """
    try:
      self.backends = []
      self.errors = []
      xml_root = ElementTree.fromstring(xml_str)

      for child in xml_root.getchildren():
        self.ProcessBackendNode(child)

      if self.errors:
        raise AppEngineConfigException('\n'.join(self.errors))

      return self.backends
    except ElementTree.ParseError:
      raise AppEngineConfigException('Bad input -- not valid XML')
tests.py 文件源码 项目:Qt.py 作者: mottosso 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def test_load_ui_invalidxml():
    """Tests to see if loadUi successfully fails on invalid ui files"""
    import sys
    invalid_xml = os.path.join(self.tempdir, "invalid.ui")
    with io.open(invalid_xml, "w", encoding="utf-8") as f:
        f.write(u"""
        <?xml version="1.0" encoding="UTF-8"?>
        <ui version="4.0" garbage
        </ui>
        """)

    from xml.etree import ElementTree
    from Qt import QtWidgets, QtCompat
    app = QtWidgets.QApplication(sys.argv)
    assert_raises(ElementTree.ParseError, QtCompat.loadUi, invalid_xml)
    app.exit()
binding.py 文件源码 项目:SplunkForPCAP 作者: DanielSchwartz1 项目源码 文件源码 阅读 38 收藏 0 点赞 0 评论 0
def __init__(self, response, _message=None):
        status = response.status
        reason = response.reason
        body = response.body.read()
        try:
            detail = XML(body).findtext("./messages/msg")
        except ParseError as err:
            detail = body
        message = "HTTP %d %s%s" % (
            status, reason, "" if detail is None else " -- %s" % detail)
        Exception.__init__(self, _message or message)
        self.status = status
        self.reason = reason
        self.headers = response.headers
        self.body = body
        self._response = response
xml.py 文件源码 项目:faze 作者: KhasMek 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def validatenmapxml(phase1):
        for file in os.listdir(phase1):
            file = os.path.join(phase1, file)
            files_to_parse = ParseConfig().files_to_parse
            try:
                ET.parse(file)
                logging.debug("Adding {f} to list of files to parse"
                              .format(f=file))
                files_to_parse.append(file)
            except ParseError:
                logging.warning("{f} is malformed or not an xml".format(f=file))
                print("{e} {f} is malformed or not an xml".format(e=cterr, f=file))
                pass
            except IOError:
                # File is a directory.
                pass
        return files_to_parse
message.py 文件源码 项目:wxpy 作者: youfou 项目源码 文件源码 阅读 69 收藏 0 点赞 0 评论 0
def location(self):
        """
        ????????????
        """
        try:
            ret = ETree.fromstring(self.raw['OriContent']).find('location').attrib
            try:
                ret['x'] = float(ret['x'])
                ret['y'] = float(ret['y'])
                ret['scale'] = int(ret['scale'])
                ret['maptype'] = int(ret['maptype'])
            except (KeyError, ValueError):
                pass
            return ret
        except (TypeError, KeyError, ValueError, ETree.ParseError):
            pass

    # chats
Bonjour.py 文件源码 项目:enigma2-plugins 作者: opendreambox 项目源码 文件源码 阅读 16 收藏 0 点赞 0 评论 0
def __parse(self, file):
        print "[Bonjour.__parse] parsing %s%s" %(self.AVAHI_SERVICES_DIR, file)
        try:
            config = cet_parse(self.AVAHI_SERVICES_DIR + file).getroot()
        except ParseError: #parsing failed, skip the file
            return

        name = config.find('name').text

        service = config.find('service')
        type = service.find('type').text
        port = service.find('port').text
        text = service.findall('txt-record')
        textList = []
        if text != None:
            for txt in text:
                textList.append(txt.text)

        service = self.buildServiceFull(file, name, type, port, textList)
        self.registerService(service)
binding.py 文件源码 项目:elasticsplunk 作者: brunotm 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def __init__(self, response, _message=None):
        status = response.status
        reason = response.reason
        body = response.body.read()
        try:
            detail = XML(body).findtext("./messages/msg")
        except ParseError as err:
            detail = body
        message = "HTTP %d %s%s" % (
            status, reason, "" if detail is None else " -- %s" % detail)
        Exception.__init__(self, _message or message)
        self.status = status
        self.reason = reason
        self.headers = response.headers
        self.body = body
        self._response = response
animelist.py 文件源码 项目:Jumper-Cogs 作者: Redjumpman 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def fetch_user_mal(self, name, url, cmd):
        with aiohttp.ClientSession() as session:
            async with session.get(url.format(name)) as response:
                data = await response.text()
                try:
                    root = ET.fromstring(data)

                except ET.ParseError:
                    return '', ''

                else:
                    if len(root) == 0:
                        return '', ''

                    collection = {x.find('series_title').text for x in root.findall(cmd)}
                    entry = root.find('myinfo')
                    if cmd == "anime":
                        info = [entry.find(x).text for x in ['user_watching', 'user_completed',
                                                             'user_onhold', 'user_dropped',
                                                             'user_days_spent_watching']]
                        return collection, info
                    else:
                        info = [entry.find(x).text for x in ['user_reading', 'user_completed',
                                                             'user_onhold', 'user_dropped',
                                                             'user_days_spent_watching']]
                        return collection, info
ntb_publish_service.py 文件源码 项目:superdesk-ntb 作者: superdesk 项目源码 文件源码 阅读 16 收藏 0 点赞 0 评论 0
def get_filename(cls, item):
        # we reparse formatted item to get filename from <meta name="filename"> element
        # this way we are sure that we have the exact same filename
        try:
            xml = ET.fromstring(item['formatted_item'])
        except (KeyError, ET.ParseError) as e:
            filename = None
            logger.error("Error on parsing, can't get filename: {}".format(e))
        else:
            filename = xml.find('head/meta[@name="filename"]').attrib['content']
        if not filename:
            return super(NTBPublishService, cls).get_filename(item)
        return filename
dataLoading.py 文件源码 项目:AlmostSignificant 作者: bartongroup 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def parseDemultiplexConfig( demultiplexConfigFile ):
    """Parses the DemultiplexConfig file for the version of casava used

        Output is the details of the software in the format:
        [softwareName, softwareVersion, softwareArguements]
        [bcl2fastq, 1.8.4, "cluster/gsu/data/hiseq/140506_SN7001398_0099_BC4362ACXX/Data/Intensities/BaseCalls --output-dir /cluster/gsu/data/processed/hiseq/140506_SN7001398_0099_BC4362ACXX/ --sample-sheet /homes/gsupipe-x/SampleSheets/140506_SN7001398_0099_BC4362ACXX/SampleSheet_revComp_edited.csv --use-bases-mask Y*,I8n*,Y*'"]

    """
    casavaDetails = []
    try:
        print "Parsing Run Parameters"
        demultiplexConfigXML = ElementTree.parse(demultiplexConfigFile)
    except IOError:
        print "Cannot load information from %s" % demultiplexConfigFile
        raise
    except ElementTree.ParseError:
        print "Invalid XML in %s" % demultiplexConfigFile
        raise

    for softwareDetails in demultiplexConfigXML.iterfind("Software"):
        versionString = softwareDetails.attrib["Version"]
        commandArgs = softwareDetails.attrib["CmdAndArgs"]

    casavaDetails.append( versionString.split("-")[0] )
    casavaDetails.append( versionString.split("-")[1] )
    casavaDetails.append( commandArgs )

    return casavaDetails


   # for line in demultiplexConfigFile:
tunein.py 文件源码 项目:AlexaPi 作者: alexa-pi 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
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


问题


面经


文章

微信
公众号

扫码关注公众号