Reputation: 1143
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()
Upvotes: 1
Views: 1347
Reputation: 59229
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 usessys.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)
Upvotes: 1