Send input to command line prompt from Python program
Asked Answered
G

3

5

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?

Grivation answered 19/1, 2015 at 19:49 Comment(1)
stackoverflow.com/a/12982539Poliard
C
5

You can write to stdin using Popen:

from subprocess import Popen, PIPE
proc = Popen(['starcluster', 'terminate', 'cluster'], stdin=PIPE)
proc.stdin.write("y\r")
Cheap answered 19/1, 2015 at 20:19 Comment(0)
R
9

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

import pexpect
child = pexpect.spawn('starcluster terminate cluster')
child.expect('Terminate EBS cluster (y/n)?')
child.sendline('y')
Record answered 19/1, 2015 at 19:55 Comment(2)
who said it first? :) well, I deleted my answer it was less detailed than yoursPhrygian
@Phrygian That's why it took longer to write :) Thank you, sir.Record
C
5

You can write to stdin using Popen:

from subprocess import Popen, PIPE
proc = Popen(['starcluster', 'terminate', 'cluster'], stdin=PIPE)
proc.stdin.write("y\r")
Cheap answered 19/1, 2015 at 20:19 Comment(0)
T
0

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

Talion answered 19/1, 2015 at 20:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.