首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python popen()在看到python提示符时退出while循环

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

Stack Overflow用户
提问于 2020-03-03 16:48:02
回答 3查看 998关注 0票数 0

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

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

我需要的中断条件是">>>“提示没有活动。

代码语言:javascript
复制
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)
EN

回答 3

Stack Overflow用户

发布于 2020-03-03 16:56:03

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

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

票数 0
EN

Stack Overflow用户

发布于 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()退出它。

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

代码语言:javascript
复制
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
EN

Stack Overflow用户

发布于 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)

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60503306

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档