我正在运行一个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)发布于 2020-03-03 16:56:03
选项1:不是在realtime_output == ''上中断,而是在收到Python提示时中断
选项2:通过it's pretty involved to get working reliably在管道上使用非阻塞读取,而不是使用readline()
发布于 2020-03-03 16:56:33
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()')如果你想要实时输出,你需要进一步修改它。要点链接应该能让你了解如何同时读写。
发布于 2020-03-04 01:01:06
已尝试以下选项,其中read()尝试查找'\n>>>‘是中断条件,并且有效。
使用子流程导入打开的子流程,管道导入sys,迭代时间范围(30):p=Popen("python",r"my_file.py",stdout=subprocess.PIPE,stderr=subprocess.STDOUT,shell=False,
=‘utf-8’,errors=‘my_file.py’,universal_newlines=True) output.endswith= '‘while not output (’\n>>>‘):c=p.stdout.read(1) output+=c sys.stdout.write(c) Popen.terminate(p) time.sleep(1)
https://stackoverflow.com/questions/60503306
复制相似问题