简体   繁体   English

防止OpenCV函数CreateVideoWriter在Python中打印到控制台

[英]Prevent OpenCV function CreateVideoWriter from printing to console in Python

I'm using the Python bindings for OpenCV and have run into a little annoyance using CreateVideoWriter where when I call the function, it prints something similar to the below to the console and I can't seem to surpress it or ideally redirect it into a variable. 我使用的是OpenCV的Python绑定,并且使用CreateVideoWriter遇到了一些麻烦,当我调用该函数时,它会在控制台上打印类似于以下内容的内容,但我似乎无法对其进行压缩或将其重定向到变量。

Output #0, avi, to 'temp/Temp.0433.avi':
    Stream #0.0: Video: mjpeg, yuvj420p, 320x240, q=2-31, 9830 kb/s, 90k tbn, 25
 tbc

The command I'm using for testing is this: 我用于测试的命令是这样的:

self.file = cvCreateVideoWriter(nf,CV_FOURCC('M','J','P','G'),self.fps,cvSize(320,240),1)

Although in the long run this app will have a control GUI its currently console based, the function is called every minute so this means its difficult to present even a simple menu or more useful status information without this call filling up the console. 尽管从长远来看,此应用将具有当前基于其控制台的控制GUI,但该函数每分钟都会调用一次,因此这意味着即使不通过此调用将控制台填满,也很难显示简单的菜单或更有用的状态信息。

Just wondering if anyone has experienced the same and/or has any ideas how I might be able to prevent this happening or can offer pointers as to what I'm doing wrong? 只是想知道是否有人经历过和/或有任何想法我如何能够防止这种情况发生,或者可以提供关于我做错了什么的指示?

I think the easiest way for you to do this is temporarily to redirect sys.stdout while calling the messy function -- anything else will force you to change the Python bindings. 我认为最简单的方法是在调用凌乱的函数时临时重定向sys.stdout -其他任何方法都会迫使您更改Python绑定。

Fortunately, this is easy: just use a contextmanager : 幸运的是,这很容易:只需使用contextmanager

>>> import contextlib
>>> @contextlib.contextmanager
... def stdout_as(stream):
...     import sys
...     sys.stdout = stream
...     yield
...     sys.stdout = sys.__stdout__
...
>>> print("hi")
hi
>>> import io
>>> stream = io.StringIO()
>>> with stdout_as(stream):
...     print("hi")
...
>>> stream.seek(0)
0
>>> stream.read()
'hi\n'
>>> print("hi")
hi

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM