简体   繁体   中英

Send input to command line prompt from Python program

I believe this to be a very simple question, but I have been failing to find a simple answer.

I am running a python program that terminates an AWS cluster (using starcluster). I am just calling a command from my python program using subprocess, something like the following.

subprocess.call('starcluster terminate cluster', shell=True)

The actual command is largely irrelevant for my question but provides some context. This command will begin terminating the cluster, but will prompt for a yes/no input before continuing, like so:

Terminate EBS cluster (y/n)? 

How do I automate typing yes from within my python program as input to this prompt?

While possible to do with subprocess alone in somewhat limited way , I would go with pexpect for such interaction, eg:

import pexpect
child = pexpect.spawn('starcluster terminate cluster')
child.expect('Terminate EBS cluster (y/n)?')
child.sendline('y')

You can write to stdin using Popen:

from subprocess import Popen, PIPE
proc = Popen(['starcluster', 'terminate', 'cluster'], stdin=PIPE)
proc.stdin.write("y\r")

It might be simplest to check the documentation on the target program. Often a flag can be set to answer yes to all prompts, eg, apt-get -y install .

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