Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 871
lbrendanl Avatar asked Dec 11 '22 01:12

lbrendanl


1 Answers

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')
like image 190
famousgarkin Avatar answered Jan 12 '23 00:01

famousgarkin