2015-06-09 41 views
5

不错的字符串我想要生成从Exception一个行字符串,它告诉我什么发生其中(并不需要一个完整的回溯)。下面的信息将是不错:适当的方式来获得异常

  • 文件名/行号
  • 异常类型
  • 异常描述(你str(e)得到什么)
  • 很高兴有:函数/方法/类

目前我做了以下工作:

import os 
... 
try: 
    os.nonexisting() 
except Exception as e: 
    t = e.__traceback__ 
    tbf = e.__traceback__.tb_frame 
    print('%s:%d: %s in %s(): "%s" ' % 
     os.path.basename(tbf.f_code.co_filename), 
     t.tb_lineno, 
     e.__class__.__name__, 
     tbf.f_code.co_name, e)) 

这给了我:

foo.py:203: AttributeError in foo(): "'module' object has no attribute 'nonexisting'" 

有没有打印出在这个例子中给出的细节更优雅的方式?我正在考虑s.th.像

print(e.format('%f: %l: %t %F: "%w"')) 

我想避免导入额外的模块,除了有一个完全为此目的。

回答

4

我认为traceback.format_exception_only确实是你想要的。

try: 
    os.nonexisting() 
except Exception as e: 
    print(traceback.format_exception_only(e.__class__, e)) 
+0

它产生'[ “AttributeError的: '模块' 对象没有属性 '不存在的' \ n” 个]'不是OP想要的(其中,是文件名,行号,功能/方法的名字吗?)。 – jfs

+0

事实上,问题是将文件/行号信息添加到'format_exception()'而没有弄乱'sys.exc_info()','extract_tb'等内部。 – frans