There are a lot of good answers on Stack Overflow about how to handle output with subprocesses, async IO, and avoiding deadlock with PIPE. Something is just not sinking in for me though; I need some guidance on how to accomplish the following.
I want to run a subprocess from my python program. The subprocess generates a ton of standard output, and a little bit of standard error if things go bad. The subprocess itself takes about 20 minutes to complete. For the output and error generated, I want to be able to both log it to the terminal, and write it to a log file.
Doing the latter was easy. I just opened two files and set then as stdout and stderr on the Popen object. However, also capturing the output as lines so that I may print them continuously to terminal has me vexed. I was thinking I could use the poll() method to continuously poll. With this though, I'd still need to use PIPE for stdout and stderr, and call read() on them which would block until EOF.
I think what I'm trying to accomplish is this:
start the subprocess
while process is still running
if there are any lines from stdout
print them and write them to the out log file
if there are any lines from stderr
print them and write them to the err log file
sleep for a little bit
Does that seem reasonable? If so, can someone explain how one would implement the 'if' parts here without blocking.
Thanks