简体   繁体   English

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

[英]Python: How to write error in the console in txt file?

I have a python script which every 10 minutes sends me an email with everything written in the console.我有一个 python 脚本,它每 10 分钟向我发送一封电子邮件,所有内容都写在控制台中。 I am running this with the crontab in my ubuntu 18.04 vps.我在我的 ubuntu 18.04 vps 中使用 crontab 运行它。 Sometimes it doesn't send the mail so I assume that when an error happens execution stops but how can I get the errors to be written in a txt file so I can analyze the error ?有时它不发送邮件,所以我假设发生错误时执行停止,但我怎样才能将错误写入 txt 文件以便分析错误?

Logging Module记录模块

To demonstrate the approach with the logging module, this would be the general approach为了演示使用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

And if I cat file_dir.txt如果我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 to File打印到文件

As I pointed out in the comments, you could accomplish this with print as well (I'm not sure you will be applauded for it)正如我在评论中指出的那样,您也可以使用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

Note that logging.exception includes the traceback in this case, which is one of the many huge benefits of that module请注意,在这种情况下logging.exception包括回溯,这是该模块的众多巨大好处之一

Edit编辑

In the interest of completeness, the traceback module leverages a similar approach as print , where you can supply a file handle:为了完整起见, 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)

This will include all of the information you want from logging这将包括您想要从logging中获取的所有信息

You can use the logging module as suggested in the comments (possibly superior but outside the scope of my knowledge), or catch the errors with try and except like:您可以按照评论中的建议使用logging模块(可能更好,但超出了我的知识范围),或者使用try捕获错误, except

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)"

Although this is generally frowned upon to catch all exceptions, because then should your program fail for whatever reason it will get gobbled up in the except clause so a better approach is to figure out what specific error you are encountering like IndexError and then just catch this specific error like:尽管通常不赞成捕获所有异常,但是如果您的程序由于某种原因失败,它将在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)"

To be able to debug and not only know the kind of error that happened, you can also get the error stack using traceback module (usually in the starting package of modules):为了能够调试并且不仅知道发生的错误类型,您还可以使用 traceback 模块(通常在模块的启动包​​中)获取错误堆栈:

import traceback
try:
    my_function()
except Exception as e:
    print(e)
    traceback.print_exc()

And then run your code 'my_code.py' in console usig >>然后在控制台使用中运行您的代码“my_code.py”>>

python my_code.py >> my_prints.txt

All the prints of your code will then be written in this .txt file, including the printed error and its stack.然后,您的代码的所有打印都将写入此 .txt 文件,包括打印的错误及其堆栈。 This is very interesting in your case or while running code on a docker if you want to detach yourself from it with ctrl+p+q and still know what is printed.如果您想使用 ctrl+p+q 将自己与它分离并且仍然知道打印的内容,这在您的情况下或在 docker 上运行代码时非常有趣。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM