如何使用脚本将stdoutredirect到文件和控制台?

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

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

在脚本内我尝试过:

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

但是这不显示屏幕上的标准输出。

我已经听说过日志logging模块,但是我不能使用这个模块来完成这个工作。

您可以在执行python文件时使用shellredirect:

 python foo_bar.py > file 

这将把所有打印在stdout上的结果从python源文件写入日志文件。

或者如果你想从脚本中logging:

 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" 

这将写入“你好”到标准输出和日志文件

我得到了将输出redirect到控制台以及同时redirect到文本文件的方式:

 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) 

使用日志模块进行debugging并关注您的应用程序

这是我如何设法login到文件和控制台/标准输出

 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

我devise了一个简单的解决scheme。 只要定义一个函数,将打印到文件或屏幕或两者。 在下面的示例中,我允许用户input输出文件名作为参数,但这不是必需的:

 OutputFile= args.Output_File OF = open(OutputFile, 'w') def printing(text): print text if args.Output_File: OF.write(text + "\n") 

在此之后,打印文件和/或屏幕所需的全部内容是:打印(Line_to_be_printed)

根据Amith Koujalgi的回答 ,这里有一个简单的模块可以用于日志logging –

transcript.py:

 """ Transcript - direct print output to a file, in addition to terminal. Usage: import transcript transcript.start('logfile.log') print("inside file") transcript.stop() print("outside file") """ import sys class Transcript(object): def __init__(self, filename): self.terminal = sys.stdout self.logfile = open(filename, "a") def write(self, message): self.terminal.write(message) self.logfile.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 def start(filename): """Start transcript, appending print output to given filename""" sys.stdout = Transcript(filename) def stop(): """Stop transcript and return print functionality to normal""" sys.stdout.logfile.close() sys.stdout = sys.stdout.terminal 

要将输出redirect到文件和terminal,而不修改Python脚本在外部使用的方式,可以使用pty.spawn(itself)

 #!/usr/bin/env python """Redirect stdout to a file and a terminal inside a script.""" import os import pty import sys def main(): print('put your code here') if __name__=="__main__": sentinel_option = '--dont-spawn' if sentinel_option not in sys.argv: # run itself copying output to the log file with open('script.log', 'wb') as log_file: def read(fd): data = os.read(fd, 1024) log_file.write(data) return data argv = [sys.executable] + sys.argv + [sentinel_option] rc = pty.spawn(argv, read) else: sys.argv.remove(sentinel_option) rc = main() sys.exit(rc) 

如果pty模块不可用(在Windows上),那么你可以用teed_call()函数replace它, teed_call()函数更加便携,但它提供了普通pipe道而不是伪terminal – 它可能会改变一些程序的行为。

基于pty.spawnpty.spawn的解决scheme比用类似文件的对象replacesys.stdout的优点在于,它们可以在文件描述符级别捕获输出,例如脚本启动其他进程也可以产生输出标准输出/标准错误。 看到我对相关问题的回答: 将stdoutredirect到Python中的文件?

我试过这个:

 """ Transcript - direct print output to a file, in addition to terminal. Usage: import transcript transcript.start('logfile.log') print("inside file") transcript.stop() print("outside file") """ import sys class Transcript(object): def __init__(self, filename): self.terminal = sys.stdout, sys.stderr self.logfile = open(filename, "a") def write(self, message): self.terminal.write(message) self.logfile.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 def start(filename): """Start transcript, appending print output to given filename""" sys.stdout = Transcript(filename) def stop(): """Stop transcript and return print functionality to normal""" sys.stdout.logfile.close() sys.stdout = sys.stdout.terminal sys.stderr = sys.stderr.terminal 

您可以使用>> python和print rint的“chevron”语法将输出redirect到文件,如文档中所示

让我们看看,

 fp=open('test.log','a') # take file object reference print >> fp , "hello world" #use file object with in print statement. print >> fp , "every thing will redirect to file " fp.close() #close the file 

结帐文件test.log你将有数据,并在控制台上打印只需使用普通打印语句。