2014-02-24 210 views
0

我最近想要一点python代码,它允许我输出到控制台和一个具有相同打印语句的日志文件。 googleing后,我发现this网站提供了一个很好的解决方案。但是,我希望能够在每次写入后刷新输出缓冲区,以便在日志文件中查看它。我将如何着手将其添加到这个类中?Python刷新打印语句

我曾尝试以下设置...

class output_file(object): 
    def __init__(self, stdout, filename): 
    silentremove(filename) 
    self.stdout = stdout 
    self.logfile = open(filename, "a") 

def write(self, text): 
    self.stdout.write(text) 
    self.logfile.write(text) 
    sys.stdout.flush() 

    def flush(self): 
    sys.stdout.flush() 

    def close(self): 
    self.stdout.close() 
    self.logfile.close() 

这是在导致flush函数调用自身循环的错误。

class output_file(object): 
    def __init__(self, stdout, filename): 
    silentremove(filename) 
    self.stdout = stdout 
    self.logfile = open(filename, "a") 

    def write(self, text): 
    self.stdout.write(text) 
    self.logfile.write(text) 
    self.stdout.flush() 

    def flush(self): 
    sys.stdout.flush() 

    def close(self): 
    self.stdout.close() 
    self.logfile.close() 

这并没有冲洗它。

+4

不回答这个问题,但你可能想看看日志模块。要做你想做的事情,你可以为同一个记录器定义两个处理程序(一个用于控制台,另一个用于文件) – RedBaron

+0

@RedBaron这正是我最初想要的。如果您将其作为答案提交,我会接受它。 – Marmstrong

+0

从技术上讲,这不是你的问题的答案,所以不适合我发布。对于未来的访问者,你可以在你的问题中发布一个结语,解释'logging'如何帮助你克服原来的问题(导致这个问题) – RedBaron

回答

3

以下以非缓冲模式重新打开sys.stdout。之后,每个stdout.writeprint将自动刷新(即打印到标准输出)。

import sys 
import os 

# Flush STDOUT continuously 
sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0) 

os.fdopen的第三个参数是缓冲的说法,是0缓冲,1被行缓冲和>1将导致(约),其大小的缓冲液(以字节为单位),<0将使用系统默认。

+0

为了以后恢复到sys.stdout的原始行为:sys.stdout仍然可用SYS .__ stdout__。 – jrouquie

+0

sys.stdout = os.fdopen(sys.stdout.fileno(),'w',1) – Gio

+0

更全面的答案在这里:http://stackoverflow.com/questions/107705/python-output-buffering – jrouquie