Skip to main content
 首页 » 编程设计

python之如何使用脚本将标准输出重定向到文件和控制台

2024年02月27日35yxwkf

我想运行 python 脚本并捕获文本文件上的输出,并希望在控制台上显示。

我想将其指定为 python 脚本本身的属性。不要使用命令 echo "hello world" | tee test.txt每次都在命令提示符下。

在我尝试过的脚本中:

sys.stdout = open('log.txt','w') 

但这不会在屏幕上显示标准输出输出。

我听说过日志记录模块,但我无法使用该模块来完成这项工作。

请您参考如下方法:

您可以在执行 Python 文件时使用 shell 重定向:

python foo_bar.py > file 

这会将 Python 源文件中打印在 stdout 上的所有结果写入日志文件。

或者,如果您想从脚本内进行日志记录:

import sys 
 
class Logger(object): 
    def __init__(self): 
        self.terminal = sys.stdout 
        self.log = open("logfile.log", "a") 
    
    def write(self, message): 
        self.terminal.write(message) 
        self.log.write(message)   
 
    def flush(self): 
        # this flush method is needed for python 3 compatibility. 
        # this handles the flush command by doing nothing. 
        # you might want to specify some extra behavior here. 
        pass     
 
sys.stdout = Logger() 

现在您可以使用:

print "Hello" 

这会将“Hello”写入标准输出和日志文件。