在open()'中使用Python'要写入日志,如何将异常写入日志? [英] Using Python's 'with open()' To Write a Log, How Can I Write Exceptions to my Log?

查看:101
本文介绍了在open()'中使用Python'要写入日志,如何将异常写入日志?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为在命令窗口中运行的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.

推荐答案

为什么不显式捕获异常并将其重新抛出:

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.

这篇关于在open()&amp;#39;中使用Python&amp;#39;要写入日志,如何将异常写入日志?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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