简体   繁体   中英

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?

@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()

Something like this:

import subprocess
process = subprocess.Popen(["yourcommand"], stdout=subprocess.PIPE)
result = process.communicate()[0]

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