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

时间:2019-03-14 18:10:12

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

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

2 个答案:

答案 0 :(得分: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的所有信息

答案 1 :(得分: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)"