Python Sys获取异常行号

时间:2019-03-04 07:21:06

标签: python

使用traceback.format_exc()可以看到发生异常的真实行,即line 6

....
  File "main.py", line 6, in testDef
    raise ValueError('Value error, exit!')
ValueError: Value error, exit!

使用sys如何获取该号码,目前返回line 16而不是6

import concurrent.futures, traceback, sys
from concurrent.futures import ThreadPoolExecutor

def testDef(arg):
  if arg == 'b':
    raise ValueError('Value error, exit!')

args = ['a', 'b']
pool = ThreadPoolExecutor(2)
fs = []
for a in args:
  fs.append(pool.submit(testDef, a))
concurrent.futures.wait(fs)
for fut in fs:
    try:
      fut.result()
    except Exception as e:
      #print(traceback.format_exc())
      exc_type, exc_obj, tb = sys.exc_info()
      lineno = tb.tb_lineno # ?
      filename = tb.tb_frame.f_code.co_filename
      print('Error File "%s", line %s: %s' % (filename,lineno, e))

输出

Error File "main.py", line 16: Value error, exit!

1 个答案:

答案 0 :(得分:0)

我找到了答案,我必须遍历tb_next

lineno = tb.tb_lineno
if tb.tb_next:
    tb_next = tb.tb_next
    while tb_next:
        lineno = tb_next.tb_lineno
        tb_next = tb_next.tb_next