python类ParseError()的实例源码

svn.py 文件源码 项目:bob 作者: BobBuildTool 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def _scanDir(self, workspace, dir):
        self.__dir = dir
        try:
            info = ElementTree.fromstring(subprocess.check_output(
                ["svn", "info", "--xml", dir],
                cwd=workspace, universal_newlines=True))
            self.__url = info.find('entry/url').text
            self.__revision = int(info.find('entry').get('revision'))
            self.__repoRoot = info.find('entry/repository/root').text
            self.__repoUuid = info.find('entry/repository/uuid').text

            status = subprocess.check_output(["svn", "status", dir],
                cwd=workspace, universal_newlines=True)
            self.__dirty = status != ""
        except subprocess.CalledProcessError as e:
            raise BuildError("Svn audit failed: " + str(e))
        except OSError as e:
            raise BuildError("Error calling git: " + str(e))
        except ElementTree.ParseError as e:
            raise BuildError("Invalid XML received from svn")
binding.py 文件源码 项目:mongodb-monitoring 作者: jruaux 项目源码 文件源码 阅读 27 收藏 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
binding.py 文件源码 项目:Splunk_CBER_App 作者: MHaggis 项目源码 文件源码 阅读 27 收藏 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
pipeline_parse.py 文件源码 项目:civet 作者: TheJacksonLaboratory 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def parse_XML(self, xmlfile, params, skip_validation=False, queue=None,
                  submit_jobs=True, completion_mail=True, search_path="",
                  user_override_file=None, keep_temp=False, release_jobs=True,
                  force_conditional_steps=False, delay=None, email_address=None,
                  error_email_address=None, walltime_multiplier=1,
                  write_pipeline_files=False,
                  tool_exec_mode=ToolExecModes.BATCH_STANDARD):

        try:
            self._parse_XML(xmlfile, params, skip_validation, queue, submit_jobs,
                            completion_mail, search_path, user_override_file,
                            keep_temp, release_jobs, force_conditional_steps,
                            delay, email_address, error_email_address,
                            walltime_multiplier, write_pipeline_files,
                            tool_exec_mode)
        except civet_exceptions.ParseError as e:
            print("\nError parsing XML:  {}".format(e), file=sys.stderr)
            sys.exit(1)
        except civet_exceptions.MissingFile as e:
            print(e, file=sys.stderr)
            sys.exit(1)
tool.py 文件源码 项目:civet 作者: TheJacksonLaboratory 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def file(self, e):
        atts = e.attrib

        id = atts['id']
        # Ensure that the id is unique.
        if id in self.options:
            raise civet_exceptions.ParseError("{}: file id duplicates an option"
                                              "name: ".format(os.path.basename(self.xml_file), self.id))
        if id in self.tool_files:
            raise civet_exceptions.ParseError("{}: file id is a duplicate: {}".format(os.path.basename(self.xml_file), self.id))


        PipelineFile.parse_xml(e, self.tool_files)

        # Track all the tool temporary files, so that we can
        # delete them at the end of the tool's execution.
        if self.tool_files[id].is_temp:
            self.tempfile_ids.append(id)
utils.py 文件源码 项目:eitbapi 作者: erral 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def xml_to_dict(data):
    try:
        root = ET.fromstring(data)
    except ET.ParseError:
        root = []
    d = {}
    for item in root:
        dd = {}
        for subitem in item:
            m = {}
            m['text'] = subitem.text
            m.update(subitem.attrib)
            dd[subitem.tag] = m

        d[dd['title']['text']] = dd

    return d
ironclaw_driver.py 文件源码 项目:warriorframework 作者: warriorframework 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def iron_claw_warrior_xml_files(filepath):
    """Validate Warrior xml files (Testcase/Testsuite/Project) against
    their xsd schema files """
    try:
        root = xml_Utils.getRoot(filepath)
    except ElementTree.ParseError, err:
        print_error("PARSING ERROR:{0}".format(err))
        return False
    ironclaw_object = IronClaw()

    if root.tag == 'Testcase':
        result = ironclaw_object.testcase_prerun(filepath)
    if root.tag == 'TestSuite':
        result = ironclaw_object.testsuite_prerun(filepath, root)
    if root.tag == 'Project':
        result = ironclaw_object.project_prerun(filepath, root)

    return result
backends_xml_parser.py 文件源码 项目:Intranet-Penetration 作者: yuxiaokui 项目源码 文件源码 阅读 21 收藏 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')
backends_xml_parser.py 文件源码 项目:MKFQ 作者: maojingios 项目源码 文件源码 阅读 21 收藏 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')
wechatUtils.py 文件源码 项目:wechat-analysis 作者: jambus 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def handleXMLContentFromMessage(content):

        rootNode = None
        if len(content) < 5:
            print ('It is not valid xml content:' + str(content))
            return rootNode
        else:
            if content[0:5] != '<msg>':
                content = '\n'.join(content.split('\n',2)[1:])

            try:    
                rootNode = ET.fromstring(content)
            except ET.ParseError as args:
                #print ('It is not valid xml content (' , args,'):\n',content)
                rootNode = None

            return rootNode
denonavr.py 文件源码 项目:denonavr 作者: scarface-4711 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def get_status_xml(self, command):
        """Get status XML via HTTP and return it as XML ElementTree."""
        # Get XML structure via HTTP get
        res = requests.get("http://{host}{command}".format(
            host=self._host, command=command), timeout=self.timeout)
        # Continue with XML processing only if HTTP status code = 200
        if res.status_code == 200:
            try:
                # Return XML ElementTree
                return ET.fromstring(res.text)
            except ET.ParseError:
                _LOGGER.error(
                    "Host %s returned malformed XML for: %s",
                    self._host, command)
                raise ValueError
        else:
            _LOGGER.error((
                "Host %s returned HTTP status code %s "
                "when trying to receive data"), self._host, res.status_code)
            raise ValueError
junos_config.py 文件源码 项目:DevOps 作者: YoLoveLife 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def guess_format(config):
    try:
        json.loads(config)
        return 'json'
    except ValueError:
        pass

    try:
        ElementTree.fromstring(config)
        return 'xml'
    except ElementTree.ParseError:
        pass

    if config.startswith('set') or config.startswith('delete'):
        return 'set'

    return 'text'
ElementTree.py 文件源码 项目:defusedxml 作者: tiran 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def _get_py3_cls():
    """Python 3.3 hides the pure Python code but defusedxml requires it.

    The code is based on test.support.import_fresh_module().
    """
    pymodname = "xml.etree.ElementTree"
    cmodname = "_elementtree"

    pymod = sys.modules.pop(pymodname, None)
    cmod = sys.modules.pop(cmodname, None)

    sys.modules[cmodname] = None
    pure_pymod = importlib.import_module(pymodname)
    if cmod is not None:
        sys.modules[cmodname] = cmod
    else:
        sys.modules.pop(cmodname)
    sys.modules[pymodname] = pymod

    _XMLParser = pure_pymod.XMLParser
    _iterparse = pure_pymod.iterparse
    ParseError = pure_pymod.ParseError

    return _XMLParser, _iterparse, ParseError
test_xml_etree.py 文件源码 项目:zippy 作者: securesystemslab 项目源码 文件源码 阅读 20 收藏 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_info()[1]
binding.py 文件源码 项目:super_simple_siem 作者: elucidant 项目源码 文件源码 阅读 32 收藏 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
xfile.py 文件源码 项目:document-api-python 作者: tableau 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def find_file_in_zip(zip_file):
    '''Returns the twb/tds file from a Tableau packaged file format. Packaged
    files can contain cache entries which are also valid XML, so only look for
    files with a .tds or .twb extension.
    '''

    candidate_files = filter(lambda x: x.split('.')[-1] in ('twb', 'tds'),
                             zip_file.namelist())

    for filename in candidate_files:
        with zip_file.open(filename) as xml_candidate:
            try:
                ET.parse(xml_candidate)
                return filename
            except ET.ParseError:
                # That's not an XML file by gosh
                pass
test_xml_etree.py 文件源码 项目:oil 作者: oilshell 项目源码 文件源码 阅读 26 收藏 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 文件源码 项目:oil 作者: oilshell 项目源码 文件源码 阅读 21 收藏 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
test_xml_etree.py 文件源码 项目:python2-tracer 作者: extremecoders-re 项目源码 文件源码 阅读 26 收藏 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 文件源码 项目:python2-tracer 作者: extremecoders-re 项目源码 文件源码 阅读 24 收藏 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
binding.py 文件源码 项目:TA-connectivity 作者: seunomosowon 项目源码 文件源码 阅读 24 收藏 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
plugin.py 文件源码 项目:haros_plugins 作者: git-afsantos 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def package_analysis(iface, scope):
    FNULL   = open(os.devnull, "w")
    output  = open(scope.id + ".xml", "w")
    try:
        subprocess.call(["cppcheck", "--xml-version=2", "--enable=all",
                            "--rule-file=" + iface.get_file("rules.xml"),
                            scope.path
                        ], stdout=FNULL, stderr=output)
    finally:
        FNULL.close()
        output.close()
    files   = file_mapping(scope)
    try:
        xml     = ET.parse(scope.id + ".xml").getroot()
        errors  = xml.find("errors")
        for error in errors:
            handle_report(iface, files, error)
    except ET.ParseError as e:
        pass
binding.py 文件源码 项目:splunk_ta_ps4_f1_2016 作者: jonathanvarley 项目源码 文件源码 阅读 29 收藏 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
binding.py 文件源码 项目:splunk_ta_ps4_f1_2016 作者: jonathanvarley 项目源码 文件源码 阅读 27 收藏 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
binding.py 文件源码 项目:TA-SyncKVStore 作者: georgestarcher 项目源码 文件源码 阅读 27 收藏 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
binding.py 文件源码 项目:TA-SyncKVStore 作者: georgestarcher 项目源码 文件源码 阅读 27 收藏 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
binding.py 文件源码 项目:cb-defense-splunk-app 作者: carbonblack 项目源码 文件源码 阅读 29 收藏 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
binding.py 文件源码 项目:cb-defense-splunk-app 作者: carbonblack 项目源码 文件源码 阅读 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
ilicache.py 文件源码 项目:projectgenerator 作者: opengisch 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def _process_ilimodels(self, file, netloc):
        '''
        Parses ilimodels.xml provided in ``file`` and updates the local repositories cache.
        '''

        try:
            root = ET.parse(file).getroot()
        except ET.ParseError as e:
            QgsMessageLog.logMessage(self.tr('Could not parse ilimodels file `{file}` ({exception})'.format(file=file, exception=str(e))), self.tr('Projectgenerator'))
            return

        self.repositories[netloc] = list()
        repo_models = list()
        for repo in root.iter('{http://www.interlis.ch/INTERLIS2.3}IliRepository09.RepositoryIndex'):
            for model_metadata in repo.findall('ili23:IliRepository09.RepositoryIndex.ModelMetadata', self.ns):
                model = dict()
                model['name'] = model_metadata.find('ili23:Name', self.ns).text
                model['version'] = model_metadata.find('ili23:Version', self.ns).text
                repo_models.append(model)

        self.repositories[netloc] = sorted(repo_models, key=lambda m: m['version'], reverse=True)
        self.models_changed.emit()
backends_xml_parser.py 文件源码 项目:xxNet 作者: drzorm 项目源码 文件源码 阅读 23 收藏 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')


问题


面经


文章

微信
公众号

扫码关注公众号