Read streaming input from subprocess.communicate()

后端 未结 7 919
攒了一身酷
攒了一身酷 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:14

    I believe the simplest way to collect output from a process in a streaming fashion is like this:

    import sys
    from subprocess import *
    proc = Popen('ls', shell=True, stdout=PIPE)
    while True:
        data = proc.stdout.readline()   # Alternatively proc.stdout.read(1024)
        if len(data) == 0:
            break
        sys.stdout.write(data)   # sys.stdout.buffer.write(data) on Python 3.x
    

    The readline() or read() function should only return an empty string on EOF, after the process has terminated - otherwise it will block if there is nothing to read (readline() includes the newline, so on empty lines, it returns "\n"). This avoids the need for an awkward final communicate() call after the loop.

    On files with very long lines read() may be preferable to reduce maximum memory usage - the number passed to it is arbitrary, but excluding it results in reading the entire pipe output at once which is probably not desirable.

提交回复
热议问题