Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting exception details in Python

I have to open & write to about 10 different files all within the same loop. e.g:

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.

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.

like image 556
user891876 Avatar asked Apr 08 '13 19:04

user891876


People also ask

How do I print exception messages in Python 3?

Python3. Method 2: By using print_exception() method. This method prints exception information and stack trace entries from traceback object tb to file.


1 Answers

You can use sys.exc_info to get information about the exception currently being handled, including the exception object itself. An IOError exception contains all of the information you need, including the filename, the errno, and a string describing the error:

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 try block will obviously still halt after the first exception.

like image 81
Cairnarvon Avatar answered Oct 02 '22 13:10

Cairnarvon