gpt4 book ai didi

python - 在 python 中,如何检查 subprocess.Popen 对象的标准输出是否有任何可读内容?

转载 作者:太空宇宙 更新时间:2023-11-03 14:33:11 24 4
gpt4 key购买 nike

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

有什么想法吗?

最佳答案

你需要将文件描述符设置为非阻塞的,你可以使用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

当没有可用数据时,readline() 将引发一个IOError

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

关于python - 在 python 中,如何检查 subprocess.Popen 对象的标准输出是否有任何可读内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6985389/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com