简体   繁体   中英

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.

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.

You should use the pexpect module for all complicated subprocessing. 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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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