2

In my Python 3 script I am starting another program that normally prints out what its doing as its doing if I don't capture the output with PIPE such as below:

proc = subprocess.run("program")

But when I do capture the output for saving to a text file with:

proc = subprocess.run("program", stdout=subprocess.PIPE, stderr=subprocess.STDOUT)

it no longer prints out as the subprocess is running but does capture the output for saving to a text file. Is there a way to have the program print to the screen and capture that output. I have read through subprocess but I cannot figure out a way to do so.

martineau
  • 119,623
  • 25
  • 170
  • 301

1 Answers1

2

Is there a way to have the program print to the screen and capture that output.

Capture it and print it yourself.

If you want to print the output as it's going, use subprocess.Popen, then stdout and stderr will be streams, you can read their content in a loop and print that as it gets output (though beware that the process's stdout will most likely be fully buffered while stderr is unbuffered).

Masklinn
  • 34,759
  • 3
  • 38
  • 57
  • Thank you I should have noticed it was a stream. I used your answer and part of https://stackoverflow.com/a/4417735/12130908 to get to a solution for both capturing and printing the output. – dylbo_baggins Jan 31 '20 at 11:37