在 Python 中获取异常详细信息
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15887038/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Getting exception details in Python
提问by user891876
I have to open & write to about 10 different files all within the same loop. e.g:
我必须在同一个循环中打开和写入大约 10 个不同的文件。例如:
for i in range(0,10):
try:
a=5
file1 = open("file1.txt",'w+')
file2 = open("file2.txt",'w+')
#... etc
print(str(a),file=file1)
print(str(a)+"hi",file=file2)
# ... etc
except:
#error handling
Now what I'd like to do is be able to get specific exception information such as what file was being opened/written to within the general exception. From my current understanding, I'd have to do something like this to achieve what I want:
现在我想做的是能够获取特定的异常信息,例如在一般异常中打开/写入的文件。根据我目前的理解,我必须做这样的事情才能实现我想要的:
for i in range(0,5):
a=5
try:
file1 = open("file1.txt",'w+')
print(str(a),file=file1)
except:
#error handling for file1
try:
file2 = open("file2.txt",'w+')
print(str(a)+"hi",file=file2)
except:
#error handling for file2
...Which is going to get extremely clunky and unattractive when I have to do this for about 10 different files. Is there any way to get (for example) the filename info out of a general exception like in my first example? Basically so the exception could report things like "error when writing to file1" without a try/except specifically for file1 operations.
...当我必须为大约 10 个不同的文件执行此操作时,这将变得非常笨拙且没有吸引力。有什么方法可以从我的第一个示例中的一般异常中获取(例如)文件名信息?基本上,异常可以报告诸如“写入文件 1 时出错”之类的内容,而没有专门针对文件 1 操作的 try/except。
edit: This is a massive over-simplification of the data being written to the file. str(a) and str(a)+"hi" are not really good representations of the data actually being written; file1 may need a hardcoded integer, where file2 may need a string formatted with multiple variables. to generalize the opening/writing process into a loop isn't going to work very nicely.
编辑:这是写入文件的数据的大量过度简化。str(a) 和 str(a)+"hi" 并不能很好地表示实际写入的数据;file1 可能需要一个硬编码的整数,而 file2 可能需要一个用多个变量格式化的字符串。将打开/写入过程概括为循环不会很好地工作。
回答by BrenBarn
You mention using a loop, but you're not actually using a loop. Use a loop. That way you can write each file, one at a time, inside a single tryblock. You don't appear to be doing anything with the files except write one value to each, so you don't need to keep them all open.
您提到使用循环,但实际上并没有使用循环。使用循环。这样你就可以在一个try块中一次写入一个文件。除了向每个文件写入一个值外,您似乎没有对这些文件执行任何操作,因此您无需将它们全部打开。
for filename in ['file1.txt', 'file2.txt', ...]:
try:
with open(filename, 'w+') as f:
f.write(str(a)+"whatever")
except IOError:
print("Error occurred with", filename)
Edit: If you have wildly different things to write to the different files, create a dictionary or other data structure ahead of time storing the mapping between files and data, then use that in the loop.
编辑:如果你有截然不同的东西要写入不同的文件,提前创建一个字典或其他数据结构来存储文件和数据之间的映射,然后在循环中使用它。
data = {'file1.txt': str(a), 'file2.txt': 'something else', 'file3.txt': str(a)+str(b)}
for filename, output in data.items():
try:
with open(filename, 'w+') as f:
f.write(output)
except IOError:
print("Error occurred with", filename)
回答by Cairnarvon
You can use sys.exc_infoto get information about the exception currently being handled, including the exception object itself. An IOErrorexception contains all of the information you need, including the filename, the errno, and a string describing the error:
您可以使用sys.exc_info获取有关当前正在处理的异常的信息,包括异常对象本身。一个IOError例外,包含了所有你需要的信息,包括文件名,错误号,以及一个描述错误的字符串:
import sys
try:
f1 = open('example1')
f2 = open('example2')
except IOError:
type, value, traceback = sys.exc_info()
print('Error opening %s: %s' % (value.filename, value.strerror))
Execution in the tryblock will obviously still halt after the first exception.
try在第一个异常之后,块中的执行显然仍然会停止。
回答by ranaalisaeed
When using exc_type, value, exc_traceback = sys.exc_info(), note that the filename that generated the exception can be obtained through the following:
使用exc_type, value, exc_traceback = sys.exc_info()时注意,产生异常的文件名可以通过以下方式获取:
exc_traceback.tb_frame.f_locals.get('filename')

