Python lxml:调用etree.iterparse(f)时获取文件当前行号
由于没有人回答或评论这篇文章,我决定重写这篇文章 考虑以下使用lxml的Python代码: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)
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