我需要能够在Python中启动一个长期运行的过程。当进程运行时,我需要将输出管道输送到我的Python应用程序中,以便在UI中显示它。UI还需要能够杀死进程。
我做了很多研究。但我还没找到办法把这三件事都做好。
subprocess.popen()允许我启动一个进程,并在需要时终止它。但是它不允许我在进程完成之前查看它的输出。而我所监测的过程从来没有单独完成过。
os.popen()允许我启动一个进程,并在它运行时监视它的输出。但我不知道怎么杀死它。我通常处于readline()调用的中间。
在使用os.popen()时,是否有方法在调用read()或readline之前知道缓冲区中是否有任何数据?例如..。
output = os.popen(command)
while True:
# Is there a way to check to see if there is any data available
# before I make this blocking call? Or is there a way to do a
# non-blocking read?
line = output.readline()
print(line)
提前谢谢。
发布于 2021-12-16 08:54:21
我建议使用subprocess.Popen对进程进行细粒度控制。
import subprocess
def main():
try:
cmd = ['ping', '8.8.8.8']
process = subprocess.Popen(
cmd,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
universal_newlines=True,
bufsize=1,
text=True
)
while True:
print(process.stdout.readline().strip())
except KeyboardInterrupt:
print('stopping process...')
process.kill()
if __name__ == '__main__':
main()
stdout
和stderr
kwargs设置为subprocess.PIPE
允许您通过.communicate
读取各自的流,而不是将它们打印到父流(因此它们会出现在运行脚本的终端中).kill()
允许您在任何时候终止进程。process.stdout
和process.stderr
可以在任何时候被查询以获得它们的当前行,通过readline()
,或者通过read()
或readlines()
获取任意数量的缓冲区内容。https://stackoverflow.com/questions/70382310
复制