如何检查子进程输出以获取提示

2024-09-26 22:50:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在python中运行一个子流程,我想检查流程的输出,直到我看到它提示输入,然后我想写入它。我原本以为我可以做到:

cmd = "my_command arg1 arg2"

with subprocess.Popen(
    shlex.split(cmd),
    stdin=subprocess.PIPE,
    stdout=subprocess.PIPE,
    bufsize=1,
    universal_newlines=True,
) as proc:
    for line in proc.stdout:
        print(line, end='')
        if line.strip() == 'Continue? [y/N]':
            proc.stdin.write("y\n")
    # do other stuff

但是我意识到这是行不通的,因为提示符本身后面没有换行符,所以for循环将无限期地阻塞。实现我想要的目标的正确和最好的方法是什么


Tags: cmdformywithstdinstdoutline流程

热门问题