简体   繁体   English

Python Sys获取异常行号

[英]Python Sys get exception line number

with traceback.format_exc() I can see real line that exception happened, which is line 6 使用traceback.format_exc()我可以看到发生异常的真实行,即line 6

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

with sys how I can get that number, currently it return line 16 not 6 使用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))

output 产量

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

I found the answer, I have to loop through tb_next 我找到了答案,我必须遍历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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM