Real-time intercepting of stdout from another process in Python

前端 未结 2 1479
北荒
北荒 2020-12-01 20:00

I\'d like to run a system process, intercept the output, and modify it real-time, line by line, in a Python script.

My best attempt, which waits for the process to c

2条回答
  •  我在风中等你
    2020-12-01 20:48

    This whole thing can be encapsulated in an iterator as:

    def subprocess_readlines(out):
        while True:
            line = out.readline()
            if not line:
                return
            yield line
    

    And called as:

    for line in subprocess_readlines(proc.stdout):
        print ">>>", line.rstrip()
    

提交回复
热议问题