Using Python's 'with open()' To Write a Log, How Can I Write Exceptions to my Log?

半腔热情 提交于 2019-12-08 03:49:34

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!