简体   繁体   English

将控制台 output 保存在 txt 文件中

[英]Save console output in txt file as it happens

I want to save my console output in a text file , but I want it to be as it happens so that if the programm crashes, logs will be saved.我想将我的控制台 output 保存在一个文本文件中,但我希望它保持原样,这样如果程序崩溃,日志将被保存。 Do you have some ideas?你有什么想法吗?

I can't just specify file in logger because I have a lot of different loggers that are printing into the console.我不能只在记录器中指定文件,因为我有很多不同的记录器正在打印到控制台中。

I think that you indeed can use a logger, just adding a file handler, from the logging module you can read this我认为你确实可以使用一个记录器,只需添加一个文件处理程序,你可以从日志记录模块中阅读这个

As an example you can use something like this, which logs both to the terminal and to a file:作为一个例子,你可以使用这样的东西,它同时记录到终端和文件:

import logging
from pathlib import Path

root_path = <YOUR PATH>

log_level = logging.DEBUG

# Print to the terminal
logging.root.setLevel(log_level)
formatter = logging.Formatter("%(asctime)s | %(levelname)s | %(message)s", "%Y-%m-%d %H:%M:%S")
stream = logging.StreamHandler()
stream.setLevel(log_level)
stream.setFormatter(formatter)
log = logging.getLogger("pythonConfig")
if not log.hasHandlers():
    log.setLevel(log_level)
    log.addHandler(stream)

# file handler:
file_handler = logging.FileHandler(Path(root_path / "process.log"), mode="w")
file_handler.setLevel(log_level)
file_handler.setFormatter(formatter)
log.addHandler(file_handler)

log.info("test")

If you have multiple loggers, you can still use this solutions as loggers can inherit from other just put the handler in the root logger and ensure that the others take the handler from that one.如果您有多个记录器,您仍然可以使用此解决方案,因为记录器可以从其他记录器继承,只需将处理程序放在根记录器中,并确保其他记录器从该记录器中获取处理程序。

As an alternative you can use nohup command which will keep the process running even if the terminal closes and will return the outputs to the desired location:作为替代方案,您可以使用 nohup 命令,即使终端关闭也会使进程保持运行,并将输出返回到所需位置:

nohup python main.py & > log_file.out &

There are literally many ways to do this.实际上有很多方法可以做到这一点。 However, they are not all suitable for different reasons (maintainability, ease of use, reinvent the wheel, etc.).然而,由于不同的原因(可维护性、易用性、重新发明轮子等),它们并不都适用。

If you don't mind using your operating system built-ins you can:如果您不介意使用您的操作系统内置插件,您可以:

  • forward standard output and error streams to a file of your choice with python3 -u./myscript.py 2>&1 outputfile.txt .使用python3 -u./myscript.py 2>&1 outputfile.txt将标准 output 和错误流转发到您选择的文件。

  • forward standard output and error streams to a file of your choice AND display it to the console too with python3 -u./myscript.py 2>&1 tee outputfile.txt .将标准 output 和错误流转发到您选择的文件,并使用python3 -u./myscript.py 2>&1 tee outputfile.txt将其显示到控制台。 The -u option specifies the output is unbuffered (ie: whats put in the pipe goes immediately out). -u选项指定 output 是无缓冲的(即:放入 pipe 的内容会立即输出)。

If you want to do it from the Python side you can:如果您想从 Python 端进行操作,您可以:

  • use the logging module to output the generated logs to a file handle instead of the standard output.使用logging模块将生成的日志 output 生成到文件句柄而不是标准的 output。

  • override the stdout and stderr streams defined in sys ( sys.stdout and sys.stderr ) so that they point to an opened file handle of your choice.覆盖 sys 中定义的 stdout 和 stderr 流( sys.stdoutsys.stderr ),以便它们指向您选择的打开的文件句柄。 For instance sys.stdout = open("log-stdout.txt", "w") .例如sys.stdout = open("log-stdout.txt", "w")

As a personnal preference, the simpler, the better.个人喜好,越简单越好。 The logging module is made for the purpose of logging and provides all the necessary mechanisms to achieve what you want. logging模块是为了日志记录而创建的,并提供了所有必要的机制来实现你想要的。 So.. I would suggest that you stick with it.所以.. 我建议你坚持下去。 Here is a link to the logging module documentation which also provides many examples from simple use to more complex and advanced use.是一个指向logging模块文档的链接,该文档还提供了从简单使用到更复杂和高级使用的许多示例。

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

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