简体   繁体   中英

How to write exceptions traceback to a file using python

Currently, my code gives traceback exception in console as per my expectations. I want to write exceptions to a file but code is not writing any exceptions to the file. A file is created but it is blank.

except Exception as error:
    print(traceback.print_exc())
    f = open('ErrorFile.txt', 'w')
    f.write(traceback.print_exc())
    f.close()

print_exc() does not return the traceback as a string. Instead it print s it directly. From the documentation :

traceback.print_exc([limit[, file]])

This is a shorthand for print_exception(sys.exc_type, sys.exc_value, sys.exc_traceback, limit, file) . (In fact, it uses sys.exc_info() to retrieve the same information in a thread-safe way instead of using the deprecated variables.)

Therefore you should use:

traceback.print_exc(file=f)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM