Getting progress message from a subprocess

后端 未结 3 1284
闹比i
闹比i 2021-02-02 10:31

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 pro

3条回答
  •  粉色の甜心
    2021-02-02 11:20

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

提交回复
热议问题