Catch print output

久未见 提交于 2021-01-29 07:15:59

问题


I’m using opencv and there is a call for video frame reading with VideoCapture and there is print statement automatically printing errors and information on console , and I want to catch these outputs and save to a file ..

VideoCapture is not returning this statements it’s just directly printing

How do I do that ?


回答1:


I dont know if its the best way to do this but it will work.

You can read in everything your program prints into the console by typing this:

Here we print print("test-test-test-test") into the console, like opencv does it, and with p.stdout.readline() you can read it in again.

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])

Output:

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

(It reads in binary so you have to convert it to a string.)



来源:https://stackoverflow.com/questions/54055963/catch-print-output

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!