【问题标题】:Python: How to write error in the console in txt file?Python:如何在 txt 文件中的控制台中写入错误?
【发布时间】:2019-03-14 18:10:11
【问题描述】:

我有一个 python 脚本,它每 10 分钟向我发送一封电子邮件,所有内容都写在控制台中。我在我的 ubuntu 18.04 vps 中使用 crontab 运行它。 有时它不发送邮件,所以我假设发生错误时执行停止,但我怎样才能将错误写入 txt 文件以便分析错误?

【问题讨论】:

  • 使用日志包写入日志文件。
  • 你用的是什么代码?你不能把它包装在try 中并将异常保存在catch 中吗?
  • logging 是执行此操作的首选方式。如果你觉得够邪恶,你可以通过file kwarg 将文件句柄对象传递给print

标签: python python-3.x python-2.7


【解决方案1】:

日志模块

为了演示logging 模块的方法,这将是一般方法

import logging

# Create a logging instance
logger = logging.getLogger('my_application')
logger.setLevel(logging.INFO) # you can set this to be DEBUG, INFO, ERROR

# Assign a file-handler to that instance
fh = logging.FileHandler("file_dir.txt")
fh.setLevel(logging.INFO) # again, you can set this differently

# Format your logs (optional)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fh.setFormatter(formatter) # This will set the format to the file handler

# Add the handler to your logging instance
logger.addHandler(fh)

try:
    raise ValueError("Some error occurred")
except ValueError as e:
    logger.exception(e) # Will send the errors to the file

如果我cat file_dir.txt

2019-03-14 14:52:50,676 - my_application - ERROR - Some error occurred
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
ValueError: Some error occurred

打印到文件

正如我在 cmets 中指出的那样,您也可以使用print 来完成此操作(我不确定您是否会为此而鼓掌)

# Set your stdout pointer to a file handler
with open('my_errors.txt', 'a') as fh:
    try:
        raise ValueError("Some error occurred")
    except ValueError as e:
        print(e, file=fh)

cat my_errors.txt

Some error occurred

注意logging.exception 包括在这种情况下的回溯,这是该模块的众多巨大好处之一

编辑

为了完整起见,traceback 模块利用与print 类似的方法,您可以在其中提供文件句柄:

import traceback
import sys

with open('error.txt', 'a') as fh:
    try:
        raise ValueError("Some error occurred")
    except ValueError as e:
        e_type, e_val, e_tb = sys.exc_info()
        traceback.print_exception(e_type, e_val, e_tb, file=fh)

这将包括您想要从logging 获得的所有信息

【讨论】:

    【解决方案2】:

    您可以按照 cmets 中的建议使用 logging 模块(可能更好,但超出了我的知识范围),或者使用 tryexcept 捕获错误,例如:

    try:
        pass
        #run the code you currently have
    except Exception as e: # catch ALLLLLL errors!!!
        print(e) # or more likely you'd want something like "email_to_me(e)"
    

    虽然通常不赞成捕获所有异常,因为如果您的程序因任何原因失败,它将被except子句吞噬,所以更好的方法是找出您遇到的特定错误,例如 IndexError,然后捕获此特定错误,例如:

    try:
        pass
        #run the code you currently have
    except IndexError as e: # catch only indexing errors!!!
        print(e) # or more likely you'd want something like "email_to_me(e)"
    

    【讨论】:

    • 非常感谢!记录目前对我来说很难,我会​​在不久的将来研究它
    • @strangethingspy 没问题!如果这解决了您的问题,通常的做法是单击我的帖子上的复选标记以接受它作为您正在寻找的答案!当您获得 15 个代表时,您也可以为有用的答案(和问题)投票 :)
    猜你喜欢
    • 2023-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-24
    • 1970-01-01
    • 2014-02-14
    • 2013-01-13
    相关资源
    最近更新 更多