使用Python的'with open()'要写一个日志,我该怎么写我的日志的例外? [英] Using Python's 'with open()' To Write a Log, How Can I Write Exceptions to my Log?

查看:434
本文介绍了使用Python的'with open()'要写一个日志,我该怎么写我的日志的例外?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在一个在命令窗口中运行的python脚本设置一个日志文件,以便有一个记录脚本的所有输入和输出。我正在使用:

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?

似乎只有一点关于open()本身的文档。但是我不知道这是否意味着它的使用是有限的。

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.

推荐答案

为什么不明确地捕获异常并重新抛出:

$ b

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.

这篇关于使用Python的'with open()'要写一个日志,我该怎么写我的日志的例外?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆