0

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 ?

Ozgur Oz
  • 740
  • 6
  • 9
  • 1
    You could just redirect all of `stderr` to a file, using `./yourprogram 2>logfile`. Another way would be to connect `sys.stderr` to a file, like `sys.stderr = open("logfile", 'w')`, or even better using a context-manager using `with`. – Jan Christoph Terasa Jan 05 '19 at 20:37
  • 1
    Possible duplicate of [Is it possible to "hack" Python's print function?](https://stackoverflow.com/questions/49271750/is-it-possible-to-hack-pythons-print-function) – Uri Goren Jan 05 '19 at 20:41

1 Answers1

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

Tom
  • 723
  • 1
  • 7
  • 16