Getting exception details in Python

前端 未结 4 820
故里飘歌
故里飘歌 2021-02-04 00:04

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         


        
相关标签:
4条回答
  • 2021-02-04 00:42

    Use the traceback module:

    traceback.print_exc()
    
    0 讨论(0)
  • 2021-02-04 00:42

    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 try block. 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.

    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)
    
    0 讨论(0)
  • 2021-02-04 00:43

    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.

    0 讨论(0)
  • 2021-02-04 00:50

    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_traceback.tb_frame.f_locals.get('filename')
    
    0 讨论(0)
提交回复
热议问题