Python popen()在看到Python提示符时退出while循环
我正在运行一个python程序Python popen()在看到Python提示符时退出while循环,python,subprocess,popen,Python,Subprocess,Popen,我正在运行一个python程序(my_file.py),该程序在进程结束时成为python提示符。因此,我无法退出while循环p.stdout.readline()等待某些事情发生 任何关于如何在循环时中断的建议p.pole()也可能保持null,因为有一些后台自动化与my_file.py相关 我需要中断条件为“>>>”提示且无活动 import subprocess from subprocess import Popen, PIPE import sys, time for iterati
(my_file.py)
,该程序在进程结束时成为python提示符。因此,我无法退出while
循环p.stdout.readline()
等待某些事情发生
任何关于如何在循环时中断的建议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)
选项1:不要在realtime\u output=''
上中断,而是在收到Python提示时中断
选项2:使用管道上的非阻塞读取,而不是使用readline()
当它进入Python提示符时,您可以通过输入exit()
退出它
类似于此(如果您不关心实时输出):
如果想要实时输出,需要进一步修改此选项。“要点”链接应该为您提供如何同时读写的方法。尝试了以下选项,其中read()尝试查找“\n>>>”是中断条件,并且有效
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()')
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)