在 python 中,如何检查 subprocess.Popen 对象的标准输出以获取任何要读取的内容?

Mat*_*sen 5 python subprocess stdout popen readline

在 python 中,如何检查 subprocess.Popen 对象的标准输出以获取任何要读取的内容?我正在围绕一个工具编写一个包装器,该工具有时会连续运行几个小时。当运行时间超过几分钟时,在子进程的标准输出上使用 .readline() 会严重降低脚本的速度。如果有任何内容需要阅读,我需要一种更有效地检查标准输出的方法。顺便说一句,这个特定的工具一次只能写入完整的行。脚本是这样的:

    #!/usr/bin/python -u
    #thiswrap.py

    import sys, time
    from subprocess import *

    chldp = Popen(sys.argv[1], bufsize=0, stdout=PIPE, close_fds=True)
    chstdin,chstdout=chldp.stdin,chldp.stdout
    startnoti=False

    while not chldp.poll():
        rrl=chstdout.readline() # <--- this is where the problem is
        if rrl[-8:]=='REDACTED TEXT':
            sys.stdout.write(rrl[:-1]+'   \r')
            if not startnoti: startnoti=True
        else:
            if startnoti: sys.stdout.write('\n')
            sys.stdout.write(rrl)
            if startnoti: # REDACTED
            time.sleep(0.1)
        time.sleep(0.1)
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?

And*_*ark 4

您需要将文件描述符设置为非阻塞,可以使用fcntl执行此操作:

import sys, time, fcntl, os
from subprocess import *

chldp = Popen(sys.argv[1], bufsize=0, stdout=PIPE, close_fds=True)
chstdin, chstdout = chldp.stdin, chldp.stdout
fl = fcntl.fcntl(chstdout, fcntl.F_GETFL)
fcntl.fcntl(chstdout, fcntl.F_SETFL, fl | os.O_NONBLOCK)

while chldp.poll() is not None:
    try:
        rrl = chstdout.readline()
    except IOError:
        time.sleep(0.1)
        continue
    # use rrl
Run Code Online (Sandbox Code Playgroud)

当没有可用数据时,IOError将由 提出readline()

请注意,由于子进程完成时chldp.poll()可能会返回0,因此您可能应该childp.poll() is not None在您的while而不是not childp.poll().