这是我来自 Python 2 的代码,需要移植:
try:
do_something_with_file(filename)
except:
exc_type, exc_inst, tb = sys.exc_info()
exc_inst.filename = filename
raise exc_type, exc_inst, tb
通过以上代码,我可以通过检查异常是否具有“filename”属性来获取由有问题的输入文件引起的整个异常。
然而,Python3的raise已经改变。以下是2to3为上述代码提供的内容:
except Exception as e:
et, ei, tb = sys.exc_info()
e.filename = filename
raise et(e).with_traceback(tb)
这给了我另一个错误,我不认为文件名属性被保留:
in __call__
raise et(e).with_traceback(tb)
TypeError: function takes exactly 5 arguments (1 given)
我想要的是能够透明地传递异常,并附带一些信息以跟踪输入文件。我错过了Python2中的raise [exception_type[,exception_instance[,traceback]]]
- 在Python3中应该如何实现?
raise ei.with_traceback(tb)
:D - thkangfrom
语法就非常好。 - Martijn Pieters