与 python 子进程交互一次等待用户输入

Interact with python subprocess once waits for user input

我正在编写一个脚本来自动测试某个软件,作为其中的一部分,我需要检查它是否正确运行命令。

我目前正在使用子进程启动可执行文件并传递初始参数。 我的代码是:subprocess.run("program.exe get -n WiiVNC", shell=True, check=True) 据我了解,这会运行可执行文件,如果退出代码为 1,则应该 return 异常。

现在,程序启动,但在某个时刻等待用户输入,如下所示:

我的问题是,我如何使用子进程一次提交用户输入 "y",文本 "Continue with download of "WiiVNC"? (y/n) >" 出现,或者一旦程序等待用户输入。

您应该对所有复杂的子处理使用 pexpect 模块。特别是,该模块旨在处理将输入传递给当前进程以供用户回答 and/or 的复杂情况,从而允许您的脚本为用户回答输入并继续子进程。

为示例添加了一些代码:

### File Temp ### 
# #!/bin/env python
# x = input('Type something:')
# print(x)

import pexpect

x = pexpect.spawn('python temp') #Start subprocess. 
x.interact()                     #Imbed subprocess in current process. 

# or

x = pexpect.spawn('python temp') #Start subprocess.
find_this_output = x.expect(['Type something:'])
if find_this_output is 0:
    x.send('I type this in for subprocess because I found the 0th string.')

试试这个:

import subprocess

process = subprocess.Popen("program.exe get -n WiiVNC", stdin=subprocess.PIPE, shell=True)
process.stdin.write(b"y\n")
process.stdin.flush()
stdout, stderr = process.communicate()