3

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

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

任何建议都非常感谢。

4

1 回答 1

3
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
于 2013-08-13T22:24:36.710 回答