简体   繁体   English

将 Python 脚本的输出重定向到文件

[英]Redirecting the output of a Python script to a file

The python script is supposed to print some messages and also compile a code multiple times for different cases. python 脚本应该打印一些消息,并针对不同的情况多次编译代码。 The compilation process itself generates messages on the screen for each case.编译过程本身会为每种情况在屏幕上生成消息。 I intend to have the output of the script messages and the compilation process messages all displayed out as well written out in a log file so that I can look into just one file for any issues.我打算将脚本消息的输出和编译过程消息全部显示出来,并写在日志文件中,以便我可以只查看一个文件中的任何问题。

I have tried having these lines:我试过有这些行:

import sys

class Logger(object):

    def __init__(self):
        self.terminal = sys.stdout
        self.log = open("regress.log", "a")

    def write(self, message):
        self.terminal.write(message)
        self.log.write(message)

sys.stdout = Logger()

Problem with the this: This only prints the messages from the original python script but the compilation messages from the code that I try to compile from inside the scripts are not written in the file.问题在于:这仅打印来自原始 python 脚本的消息,但我尝试从脚本内部编译的代码中的编译消息未写入文件。

I have also tried simply : python script.py > output我也简单地尝试过:python script.py > output

Problem with that: The output file only consists of the compilation messages from the code within are written in "output" file.问题在于:输出文件仅包含来自写入“输出”文件中的代码的编译消息。 The messages from the script are not printed.不打印来自脚本的消息。 Also, the compilation messages are not displayed on screen as well.此外,编译消息也不会显示在屏幕上。

Essentially, I want to get all the normal print and the output of launched commands written in one single file and displayed on screen as well.本质上,我希望将所有正常打印和已启动命令的输出写入一个文件并显示在屏幕上。

您可以从命令行执行此操作:

python script_name.py > output_name

In order to do this, all it requires you to do is;为了做到这一点,你需要做的就是;

def log_msg(msg):
    log = open("C:/Path/to/File.log", "a")
    log.write(msg+"\n")
    log.close()

print "Error message"
log_msg("Error Message")

~~~~ ~~~~

Next time, please remember to post what you have tried, what you will think will work, and what didn't work, as well as some of your code.下次,请记得发布您尝试过的内容,您认为可行的内容,以及无效的内容,以及您的一些代码。

The easiest way to do something like this is to work with the standard logging system.执行此类操作的最简单方法是使用标准日志记录系统。

You'll need to append 2 handlers a StreamHandler for sys.stdout and a FileHandler for to store the content in disk.您需要附加 2 个处理程序,一个用于 sys.stdout 的 StreamHandler 和一个用于将内容存储在磁盘中的 FileHandler。

Check this for more information: https://docs.python.org/2/library/logging.html检查此以获取更多信息: https : //docs.python.org/2/library/logging.html

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

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