停止写入stdout的函数

时间:2012-04-25 18:31:57

标签: python opencv stdout

我的代码中有这一行:

writer = cv.CreateVideoWriter('video.avi', cv.CV_FOURCC('X','V','I','D'), 30 ,(480,800), 1)

用于控制此输出的输出:

Output #0, avi, to 'video.avi':
Stream #0:0: Video: mpeg4, yuv420p, 480x800, q=2-31, 24576 kb/s, 90k tbn, 30 tbc

我想阻止它将任何内容打印到stdout,但是保留在代码中自己输出更多内容的可能性。我怎样才能做到这一点?

我尝试了这个,但它没有用。

class NullStream:
    def write(self, text):
        pass

sys.stdout = NullStream()
sys.stderr = NullStream()

print "hello" #This doesn't outputs

#This function still outputs to console:
writer = cv.CreateVideoWriter('video.avi', cv.CV_FOURCC('X','V','I','D'), 30 ,(480,800), 1)

sys.stdout = sys.__stdout__
sys.stderr = sys.__stderr__

2 个答案:

答案 0 :(得分:3)

输出此信息不是OpenCV。它是FFMPEG(由OpenCV调用)。

您可以重新编译FFMPEG以禁用这些调试。

答案 1 :(得分:2)

import os
import sys
saved_stdout, saved_stderr = sys.stdout, sys.stderr
sys.stdout = sys.stderr = open(os.devnull, "w")
writer = cv.CreateVideoWriter('video.avi', cv.CV_FOURCC('X','V','I','D'), 30 ,(480,800), 1)
sys.stdout, sys.stderr = saved_stdout, saved_stderr
print 'Now this will print to stdout'

演示:

>>> import os
>>> import sys
>>> saved_stdout, saved_stderr = sys.stdout, sys.stderr
>>> sys.stdout = sys.stderr = open(os.devnull, "w")
>>> print 'hello world'                     # no output
>>> sys.stderr.write('Invisible Error!\n')  # no ouput
>>> sys.stdout, sys.stderr = saved_stdout, saved_stderr
>>> print 'goodbye world'                   
goodbye world
>>> sys.stderr.write('Error!\n')
Error!