Python:如何在txt文件中在控制台中编写错误?

问题描述 投票:0回答:2

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

python python-3.x python-2.7
2个回答
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

打印老兄

正如我在评论中指出的那样,你也可以用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信息


0
投票

您可以使用评论中建议的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)"
© www.soinside.com 2019 - 2024. All rights reserved.