gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 16:42:04 25 4
gpt4 key购买 nike

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

考虑以下使用 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 可以替换为任何可用的参数。

非常感谢任何建议。

最佳答案

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

关于python - lxml:调用etree.iterparse(f)时获取文件当前行号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18192910/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com