如何获取Python子进程的输出并在之后终止它?

如何获取Python子进程的输出并在之后终止它?,python,python-3.x,subprocess,Python,Python 3.x,Subprocess,我想获得子流程的输出。由于它无限期运行,我想在满足某些条件时终止它 当我使用check_output启动子流程时,我获得了输出,但没有用于终止流程的句柄: output = subprocess.check_output(cmd, shell=True) 当我使用Popen或run启动子流程时,我获得了一个终止流程的句柄,但没有输出 p = subprocess.Popen(cmd, shell=True, preexec_fn=os.setsid) 如何获得这两种格式?您需要告诉Popen

我想获得子流程的输出。由于它无限期运行,我想在满足某些条件时终止它

当我使用
check_output
启动子流程时,我获得了输出,但没有用于终止流程的句柄:

output = subprocess.check_output(cmd, shell=True)
当我使用
Popen
run
启动子流程时,我获得了一个终止流程的句柄,但没有输出

p = subprocess.Popen(cmd, shell=True, preexec_fn=os.setsid)

如何获得这两种格式?

您需要告诉
Popen
您想要读取标准输出,但这可能有点棘手

p = subprocess.Popen(cmd, shell=True, preexec_fn=os.setsid, stdout=subprocess.PIPE)
while True:
    chunk = p.stdout.read(1024)  # this will hang forever if there's nothing to read
p.terminate()
试试这个:

import subprocess
p = subprocess.Popen("ls -a", shell=True, stdout=subprocess.PIPE,stderr=subprocess.PIPE)
print((p.stdout.read()))
if p.stdout.read() or p.stderr.read():
    p.terminate()

什么时候才能知道您已经获得了完整的流程输出?当进程终止时。因此,无需手动终止它。只需等待它结束,使用
检查输出即可

现在,如果你想等待一个给定的模式出现,那么就终止,这是另外一回事了。只需逐行读取,如果某些模式匹配,则中断循环并结束流程

p = subprocess.Popen(cmd, shell=True, preexec_fn=os.setsid) # add stderr=subprocess.PIPE) to merge output & error
for line in p.stdout:
   if b"some string" in line:  # output is binary
       break
p.kill() # or p.terminate()

什么时候才能知道您已经获得了完整的流程输出?当进程终止时。因此,无需手动终止它。就等它结束吧。我不明白你的问题。您可能想读几行并正确终止?我既不假设一个进程自行结束,也不假设“完整进程输出”。工艺终止的条件与工艺输出无关。我想阅读输出,并随时终止。如果“whenwhere I like to”与输出中的内容相关联,请检查我的回答。我可能错了,但我认为这不起作用<代码>如果p.stdout或p.stderr始终为真。这些是文件句柄。
print(p.stdout)
除非对其执行
read()
,否则不会打印输出。@Jean-Françoisfare我已经更新了代码,现在检查一下,我想我通过读取stdout文件中的数据解决了问题。如果p.stdout.read()或p.stderr.read()
很奇怪,则不
。第一项总是错误的(因为我们已经读了上面的一行),另一项要么是空的,要么不是空的,但这不是OP所问的。“如果没有什么可读的,这将永远挂起”:好的,这将永远挂起,因为你有一个无限循环。如果不是chunk:break,则添加
,以便在进程结束时终止。