Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting progress message from a subprocess

Tags:

I want to start a program which needs several minutes to complete. During this time I want to read the progress message of the program (which are printed on the stdout). The problem is that I cannot find a way to read out its output during its run.

The only function I found to read out the output of a program is Popen.communicate(), but this method waits until the process finishes. So it is impossible to get the progress and make it visible to the user in a special formatted way.

Is it possible to do this another way?

When I run the process with subprocess.popen with my script I see the output of the program on the screen. Is it possible to hide it? (Ubuntu 10.10, normal terminal)

like image 935
tbolender Avatar asked Feb 09 '11 22:02

tbolender


People also ask

How do you find the results of a subprocess run?

To capture the output of the subprocess. run method, use an additional argument named “capture_output=True”. You can individually access stdout and stderr values by using “output. stdout” and “output.

What is the output of subprocess Check_output?

The subprocess. check_output() is used to get the output of the calling program in python. It has 5 arguments; args, stdin, stderr, shell, universal_newlines. The args argument holds the commands that are to be passed as a string.

What does subprocess Check_call return?

subprocess. check_call() gets the final return value from the script, and 0 generally means "the script completed successfully".

What is subprocess popen ()?

The subprocess module defines one class, Popen and a few wrapper functions that use that class. The constructor for Popen takes arguments to set up the new process so the parent can communicate with it via pipes. It provides all of the functionality of the other modules and functions it replaces, and more.


1 Answers

Simplest is to call Popen with the keyword argument stdout=subprocess.PIPE.

p = subprocess.Popen(["ls"], stdout=subprocess.PIPE) while True:     line = p.stdout.readline()     if not line:         break     print line 

To see this in action, here are two sample scripts. Make them both in the same directory and run python superprint.py

printandwait.py:

import time import sys print 10 sys.stdout.flush() time.sleep(10) print 20 sys.stdout.flush() 

superprint.py:

import subprocess import sys p = subprocess.Popen(["python printandwait.py"], shell=True, stdout=subprocess.PIPE) while True:     print "Looping"     line = p.stdout.readline()     if not line:         break     print line.strip()     sys.stdout.flush() 
like image 192
chmullig Avatar answered Oct 11 '22 09:10

chmullig