Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/294.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python lxml:调用etree.iterparse(f)时获取文件当前行号_Python_Parsing_Lxml - Fatal编程技术网

Python lxml:调用etree.iterparse(f)时获取文件当前行号

Python lxml:调用etree.iterparse(f)时获取文件当前行号,python,parsing,lxml,Python,Parsing,Lxml,由于没有人回答或评论这篇文章,我决定重写这篇文章 考虑以下使用lxml的Python代码: treeIter = etree.iterparse(fObj) for event, ele in treeIter: if ele.tag == 'logRoot': try: somefunction(ele) except InternalException as e: e.handle(*args)

由于没有人回答或评论这篇文章,我决定重写这篇文章

考虑以下使用lxml的Python代码:

treeIter = etree.iterparse(fObj)
for event, ele in treeIter:
    if ele.tag == 'logRoot':
        try:
            somefunction(ele)
        except InternalException as e:
            e.handle(*args)
    ele.clear()
InternalException是用户定义的,它包装了来自somefunction()的除lxml.etree.XMLSyntaxError之外的所有异常。InternalException具有定义良好的处理程序函数。handle()

fObj将“trueRoot”作为顶级标记,许多“logRoot”作为第二级叶子

我的问题是:在处理异常e时,是否有方法记录当前行号*args可以替换为任何可用的参数


非常感谢您的任何建议。

所以您想说的是:e.handle()应该将ele和格式ele.sourceline包含在消息中?您可以这样做,或者只需将
elem.sourceline
传递给
e.handle
。elem.sourceline是重要的提示
import lxml.etree as ET
import io

def div(x):
    return 1/x

content = '''\
    <trueRoot>
      <logRoot a1="x1"> 2 </logRoot>
      <logRoot a1="x1"> 1 </logRoot>
      <logRoot a1="x1"> 0 </logRoot>            
    </trueRoot>
    '''
for event, elem in ET.iterparse(io.BytesIO(content), events=('end', ), tag='logRoot'):
    num = int(elem.text)
    print('Calling div({})'.format(num))
    try:
        div(num)
    except ZeroDivisionError as e:
        print('Ack! ZeroDivisionError on line {}'.format(elem.sourceline))
Calling div(2)
Calling div(1)
Calling div(0)
Ack! ZeroDivisionError on line 4