Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I capture the stdout output of a child process?

I'm trying to write a program in Python and I'm told to run an .exe file. When this .exe file is run it spits out a lot of data and I need a certain line printed out to the screen. I'm pretty sure I need to use subprocess.popen or something similar but I'm new to subprocess and have no clue. Anyone have an easy way for me to get this done?

like image 440
Tyler Avatar asked May 28 '09 20:05

Tyler


People also ask

Does child process inherit stdout?

Because of the stdio: 'inherit' option above, when we execute the code, the child process inherits the main process stdin , stdout , and stderr . This causes the child process data events handlers to be triggered on the main process.

What is the output of child process?

The read end of one pipe serves as standard input for the child process, and the write end of the other pipe is the standard output for the child process.

How do you capture standard output in Python?

To capture stdout output from a Python function call, we can use the redirect_stdout function. to call redirect_stdout with the f StringIO object. Then we call do_something which prints stuff to stdout. And then we get the value printed to stdout with f.


1 Answers

@Paolo's solution is perfect if you are interested in printing output after the process has finished executing. In case you want to poll output while the process is running you have to do it this way:

process = subprocess.Popen(cmd, stdout=subprocess.PIPE)

while True:
    out = process.stdout.readline(1)
    if out == '' and process.poll() != None:
        break
    if out.startswith('myline'):
        sys.stdout.write(out)
        sys.stdout.flush()
like image 81
Nadia Alramli Avatar answered Oct 16 '22 03:10

Nadia Alramli