2012-03-30 51 views
10

好。所以大概一个例子就是说明这个问题抑制打印为标准输出蟒蛇

所以我有这样的一个好办法:

if __name__=="__main__" 
    result = foobar() 
    sys.stdout.write(str(result)) 
    sys.stdout.flush() 
    sys.exit(0) 

现在这个剧本正在从一个叫做红宝石脚本..基本上它解析了那里的结果。 但是foobar()有很多打印语句..并且stdout也刷新了所有这些打印。 有没有一种方法(除了记录方法)我可以修改这里的东西,自动抑制这些打印并刷新这个结果? 谢谢

回答

17

你想暂时影响(或以其他方式隐藏)标准输出。事情是这样的:

actualstdout = sys.stdout 
sys.stdout = StringIO() 
result = foobar() 
sys.stdout = actualstdout 
sys.stdout.write(str(result)) 
sys.stdout.flush() 
sys.exit(0) 

你需要指定的东西是类似文件的sys.stdout来让其他的方法可以有效地使用它。 StringIO是一个不错的选择,因为它不需要磁盘访问(它只会在内存中收集),然后被丢弃。

+0

真棒..只是什么:) – Fraz 2012-03-30 20:04:05

+4

使用'sys.stdout = open(os.devnull,'w')'而不是'StringIO()'怎么样? – ovgolovin 2012-03-30 20:07:15

+0

@ovgolovin - 绝对合理,如果没有你可能需要输出的期望。使用StringIO,您可以在重置“stdout”的原始值之前根据需要检索它。 – 2012-03-30 20:09:40

3
import sys 

class output: 
    def __init__(self): 
     self.content = [] 
    def write(self, string): 
     self.content.append(string) 


if __name__=="__main__": 

    out = output()     
    sys.stdout = out     #redirecting the output to a variable content 

    result = foobar() 
    sys.stdout.write(str(result)) 
    sys.stdout.flush() 

    sys.stdout = sys.__stdout__  #redirecting the output back to std output 
    print "o/p of foo :",out.content 

    sys.exit(0) 
6

使用Python 3.4和最多可以使用redirect_stdout contextmanager是这样的:我需要

with redirect_stdout(open(os.devnull, "w")): 
    print("This text goes nowhere") 
print("This text gets printed normally")