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

str*_*spy 5 python python-2.7 python-3.x

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

C.N*_*ivs 6

日志模块

为了演示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
Run Code Online (Sandbox Code Playgroud)

如果我 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
Run Code Online (Sandbox Code Playgroud)

打印到文件

正如我在评论中指出的那样,您也可以通过以下方式完成此操作print(我不确定您是否会为此鼓掌)

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
Run Code Online (Sandbox Code Playgroud)

cat my_errors.txt

Some error occurred
Run Code Online (Sandbox Code Playgroud)

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

编辑

为了完整起见,该traceback模块利用了与 类似的方法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)
Run Code Online (Sandbox Code Playgroud)

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