如何用脚本将stdout同时重定向到文件和控制台?
我想运行一个Python脚本,并把输出结果保存到一个文本文件里,同时也希望能在控制台上显示出来。
我想把这个功能直接写在Python脚本里,而不是每次都在命令提示符下使用命令echo "hello world" | tee test.txt
。
在脚本里我尝试了:
sys.stdout = open('log.txt','w')
但是这样做并不能在屏幕上显示输出。
我听说过有一个叫做日志模块的东西,但我用这个模块的时候没有成功。
16 个回答
21
使用日志模块来调试和跟踪你的应用程序
下面是我如何将日志记录到文件和控制台/标准输出的方法
import logging
logging.basicConfig(level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s',
filename='logs_file',
filemode='w')
# Until here logs only to file: 'logs_file'
# define a new Handler to log to console as well
console = logging.StreamHandler()
# optional, set the logging level
console.setLevel(logging.INFO)
# set a format which is the same for console use
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
# tell the handler to use this format
console.setFormatter(formatter)
# add the handler to the root logger
logging.getLogger('').addHandler(console)
# Now, we can log to both ti file and console
logging.info('Jackdaws love my big sphinx of quartz.')
logging.info('Hello world')
可以从源头了解更多信息: https://docs.python.org/2/howto/logging-cookbook.html
25
我找到了一个方法,可以同时把输出内容发送到控制台和一个文本文件中:
te = open('log.txt','w') # File where you need to keep the logs
class Unbuffered:
def __init__(self, stream):
self.stream = stream
def write(self, data):
self.stream.write(data)
self.stream.flush()
te.write(data) # Write the data of stdout here to a text file as well
sys.stdout=Unbuffered(sys.stdout)
195
你可以在执行Python文件的时候使用“shell重定向”功能:
python foo_bar.py > file
这样做会把Python程序在标准输出(也就是屏幕上显示的内容)打印的所有结果写入到一个日志文件里。
如果你想在脚本内部进行记录的话:
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”同时写到标准输出和日志文件里。