简体   繁体   English

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

[英]Interact with python subprocess once waits for user input

I'm working on a script to automate tests of a certain software, and as part of it I need to chech if it runs commands correctly.我正在编写一个脚本来自动化某个软件的测试,作为其中的一部分,我需要检查它是否正确运行命令。

I'm currently launching an executeable using subprocess and passing the initial parameters.我目前正在使用子进程启动可执行文件并传递初始参数。 My code is: subprocess.run("program.exe get -n WiiVNC", shell=True, check=True) As far as I understand, this runs the executeable, and is supposed to return an exception if the exit code is 1.我的代码是: subprocess.run("program.exe get -n WiiVNC", shell=True, check=True)据我了解,这运行可执行文件,如果退出代码为 1,则应该返回异常.

Now, the program launches, but at some point waits for user input like so:现在,程序启动,但在某些时候等待用户输入,如下所示: 所需的用户输入

My question is, how do I go about submitting the user input "y" using subprocess once either, the text "Continue with download of "WiiVNC"? (y/n) >" shows up, or once the program waits for user input.我的问题是,我如何 go 关于使用子进程提交用户输入“y”一次,文本“继续下载“WiiVNC”?(y/n)>“出现,或者一旦程序等待用户输入.

You should use the pexpect module for all complicated subprocessing.您应该使用 pexpect 模块进行所有复杂的子处理。 In particular, the module is designed to handle the complicated case of either passing through the input to the current process for the user to answer and/or allowing your script to answer the input for the user and continue the subprocess.特别是,该模块旨在处理将输入传递给当前进程以供用户回答和/或允许您的脚本为用户回答输入并继续子进程的复杂情况。

Added some code for an example:为示例添加了一些代码:

### 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.')

Try this:尝试这个:

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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM