简体   繁体   中英

Get the output of python subprocess in console

process = subprocess.check_output(BACKEND+"mainbgw setup " + str(NUM_USERS), shell=True,\
                                          stderr=subprocess.STDOUT)

I am using the above statement to run a C program in django-python based server for some computations, there are some printf() statements whose output I would like to see on stdout while the server is running and executing the subprocess, how can that be done ?

If you actually don't need the output to be available to your python code as a string, you can just use os.system , or subprocess.call without redirecting stdout elsewhere. Then stdout of your C program will just go directly to stdout of your python program.

If you need both streaming stdout and access to the output as a string, you should use subprocess.Popen (or the old popen2.popen4 ) to obtain a file descriptor of the output stream, then repeatedly read lines from the stream until you exhausted it. In the mean time, you keep a concatenated version of all data you grabbed. This is an example of the loop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM