问题
I'm setting up a log file for a python script being run in a command window so that there's a record of all the input and output from the script. I'm using:
with open("file.txt") as file:
so that it will still save all the text it has written if an exception occurs.
However I was wondering if there might be a way to get it to log the exception as well? Basically to write one last message and then close the file as the exit function?
There seemed to be only a little documentation on with open() itself. But I wasn't sure if that means its use is limited or not.
回答1:
Why not explicitly catch the exception and rethrow it:
with open("file.txt") as file:
try:
<do_something>
except Exception as e:
file.write(e)
raise
The challenge comes if the exception is generator by trying to write to file.
来源:https://stackoverflow.com/questions/29370618/using-pythons-with-open-to-write-a-log-how-can-i-write-exceptions-to-my-lo