简体   繁体   English

如何将 Python 脚本控制台 output 保存到文件中?

[英]How to save Python script console output to a file?

I want to run a Python script and save its console output to a file, while still being able to see the output in the console.我想运行 Python 脚本并将其控制台 output 保存到文件中,同时仍然能够在控制台中看到 output。 For example, a "Hello World" script as simple as print('Hello World') would show Hello World in the console and also save this output to a file.例如,像print('Hello World')这样简单的“Hello World”脚本将在控制台中显示Hello World ,并将此 output 保存到文件中。

I was previously using pythonscript.py > console_output.txt to shell redirect, I can't see anything in the console with this solution (and for some reason, it no longer saves anything to the specified file, no idea why).我以前使用pythonscript.py > console_output.txt到 shell 重定向,使用此解决方案在控制台中看不到任何内容(由于某种原因,它不再将任何内容保存到指定文件中,不知道为什么)。 This is a solution using Linux shell redirection, but now I would like to write a separate python script to do it.这是使用 Linux shell 重定向的解决方案,但现在我想编写一个单独的 python 脚本来执行此操作。

I don't think I need any special error logging stuff.我认为我不需要任何特殊的错误日志记录。 I'm currently using try: except blocks and just printing the Exception and then using that to find the error.我目前正在使用try: except块并仅打印异常,然后使用它来查找错误。

Try tee command, for example: pythonscript.py | tee console_output.txt试试tee命令,例如: pythonscript.py | tee console_output.txt pythonscript.py | tee console_output.txt

You can do you something like this:你可以这样做:

def custom_print(message_to_print, log_file='output.txt'):
    print(message_to_print)
    with open(log_file, 'a') as of:
        of.write(message_to_print + '\n')

This way you can use custom_print instead of print to be able to both see the result in the console and have the result appended to a log file.这样,您可以使用custom_print而不是print来在控制台中查看结果并将结果附加到日志文件中。

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

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