Python popen() 在看到 python 提示时退出 while 循环

Python popen() to exit while loop when see python prompt

我是 运行 一个 python 程序 (my_file.py),它在过程结束时变成 python 提示符。因此,我无法摆脱 while 循环。 p.stdout.readline() 等待某事发生。

关于如何打破 while 循环的任何建议。 p.pole() 也可能会保持 null,因为有一些与 my_file.py 相关的后台自动化。

我需要中断条件是“>>>”提示符,没有 activity。

import subprocess
from subprocess import Popen, PIPE
import sys, time
for iteration in range(25):
    p=Popen(r"python my_file.py",
            stdout=subprocess.PIPE,
            stderr=subprocess.STDOUT,
            shell=False,
            encoding='utf-8',
            errors='replace',
            universal_newlines=True)
    while True:
        realtime_output = p.stdout.readline()
        if realtime_output == '': #and p.poll() is not None:
            break
        else:
            print(realtime_output.strip(), flush=True)
    print("--------------- PythonSV session for {} iteration is complete -----------\n\n".format(iteration + 1))
    #subprocess.Popen("taskkill /F /T /PID %i" % p.pid, shell=True)
    Popen.terminate(p)
    time.sleep(1)

选项 1:不是在 realtime_output == '' 时中断,而是在收到 Python 提示时中断

选项 2:不使用 readline(),而是在管道上使用非阻塞读取,尽管 it's pretty involved to get working reliably

https://gist.github.com/waylan/2353749

当它进入Python提示时,您可以通过输入exit()退出它。

类似的东西(如果你不关心实时输出):

from subprocess import Popen, PIPE

p = Popen(["python", "my_file.py"], stdin=PIPE, stdout=PIPE, stderr=PIPE shell=True)
output, error = p.communicate(input=b'exit()')

如果你想要实时输出,你需要进一步修改这个。要点 link 应该让您了解如何同时读写。

尝试了以下选项,其中 read() 试图找到 '\n>>>' 是中断条件并且有效。

import subprocess
from subprocess import Popen, PIPE
import sys, time
for iteration in range(30):
    p=Popen(["python", r"my_file.py"],
            stdout=subprocess.PIPE,
            stderr=subprocess.STDOUT,
            shell=False,
            encoding='utf-8',
            errors='replace',
            universal_newlines=True)
    output = ''
    while not output.endswith('\n>>>'):
        c=p.stdout.read(1)
        output+=c
        sys.stdout.write(c)
    Popen.terminate(p)
    time.sleep(1)