如何使用脚本将标准输出重定向到文件和控制台? [英] How to redirect stdout to both file and console with scripting?
问题描述
我想运行一个 python 脚本并将输出捕获到一个文本文件中,并想在控制台上显示.
I want to run a python script and capture the output on a text file as well as want to show on console.
我想将它指定为 python 脚本本身的一个属性.不要使用命令 echo "hello world" |tee test.txt
每次都在命令提示符下.
I want to specify it as a property of the python script itself. NOT to use the command echo "hello world" | tee test.txt
on command prompt every time.
在我尝试过的脚本中:
sys.stdout = open('log.txt','w')
但这不会在屏幕上显示标准输出.
But this does not show the stdout output on screen.
我听说过日志模块,但我无法使用该模块来完成这项工作.
I have heard about logging module but I could not get luck using that module to do the job.
推荐答案
你可以在执行python文件时使用shell重定向:
You can use shell redirection while executing the python file:
python foo_bar.py > file
这会将所有打印在标准输出上的结果从 python 源写入文件到日志文件.
This will write all results being printed on stdout from the python source to file to the logfile.
或者如果您想从脚本中进行日志记录:
Or if you want logging from within the script:
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"写入标准输出和日志文件
This will write "Hello" to both stdout and the logfile
这篇关于如何使用脚本将标准输出重定向到文件和控制台?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!