Read streaming input from subprocess.communicate()

后端 未结 7 1231
攒了一身酷
攒了一身酷 2020-11-21 05:53

I\'m using Python\'s subprocess.communicate() to read stdout from a process that runs for about a minute.

How can I print out each line of that process

7条回答
  •  南旧
    南旧 (楼主)
    2020-11-21 06:06

    Please note, I think J.F. Sebastian's method (below) is better.


    Here is an simple example (with no checking for errors):

    import subprocess
    proc = subprocess.Popen('ls',
                           shell=True,
                           stdout=subprocess.PIPE,
                           )
    while proc.poll() is None:
        output = proc.stdout.readline()
        print output,
    

    If ls ends too fast, then the while loop may end before you've read all the data.

    You can catch the remainder in stdout this way:

    output = proc.communicate()[0]
    print output,
    

提交回复
热议问题