【问题标题】:Catch print output捕捉打印输出
【发布时间】:2019-06-01 00:43:39
【问题描述】:

我正在使用 opencv,并且调用 VideoCapture 读取视频帧,并且在控制台上有打印语句自动打印错误和信息,我想捕获这些输出并保存到文件中..

VideoCapture 没有返回此语句,它只是直接打印

我该怎么做?

【问题讨论】:

  • 您可以使用./yourprogram 2>logfile 将所有stderr 重定向到一个文件。另一种方法是将sys.stderr 连接到一个文件,例如sys.stderr = open("logfile", 'w'),或者使用上下文管理器使用with 更好。

标签: python opencv


【解决方案1】:

我不知道这是否是最好的方法,但它会起作用。

您可以通过键入以下内容将程序打印到控制台的所有内容读入:

在这里,我们将print("test-test-test-test") 打印到控制台中,就像opencv 一样,使用p.stdout.readline(),您可以再次读取它。

import os
import sys
from subprocess import Popen, PIPE, STDOUT

script_path = os.path.join('name_of_your_program.py')

p = Popen([sys.executable, '-u', script_path],
          stdout=PIPE, stderr=STDOUT, bufsize=1)

while True:
    print("test-test-test-test")

    string = p.stdout.readline() 
    print(string[0:3])

输出:

test-test-test-test
b'tes'
test-test-test-test
b"b'T"
test-test-test-test
b'tes'

(它以二进制形式读取,因此您必须将其转换为字符串。)

【讨论】:

  • 这正是我所需要的,会试一试谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-20
  • 2014-07-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多