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

问题描述 投票:0回答:3

我正在运行python程序(my_file.py),该程序在处理结束时变为python提示符。因此,我无法摆脱while循环。 p.stdout.readline()等待某些事情发生。

关于如何中断while循环的任何建议。 p.pole()也可能会保留为null,因为有一些与my_file.py相关的背景自动化。

我需要将中断条件设为“ >>>”,并且没有任何活动。

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)
python subprocess popen
3个回答
0
投票

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

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


0
投票

How can I simulate a key press in a Python subprocess?

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()')

如果要获得实时输出,则需要进一步修改。要点链接应为您提供一个如何同时读写的想法。


0
投票

尝试以下选项,其中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)
© www.soinside.com 2019 - 2024. All rights reserved.