3

Consider a command like

yum install boto

When I execute in terminal, to proceed is asks me for yes/no

Can I respond to it in python like

os.system("yum install boto")

Next "Yes" is to be passed to terminal through the same python code so that it installs. Well, I dont think this works. If it is written after tha above statement

os.system("yes")

Please tell me if this is possible?

Sailesh Kotha
  • 1,939
  • 3
  • 20
  • 27
  • possible duplicate of [Running an interactive command from within python](http://stackoverflow.com/questions/11457931/running-an-interactive-command-from-within-python) – Martin Tournoij Feb 22 '15 at 19:17
  • There's also: http://stackoverflow.com/questions/1567371/wrapping-an-interactive-command-line-application-in-a-python-script?lq=1 (and probably a few more...) I searched for: [python subprocess interactive](https://duckduckgo.com/?q=python%20subprocess%20interactive) – Martin Tournoij Feb 22 '15 at 19:17
  • 1
    There are ways to do this, but the usual solution is to use a command-line option that prevents the program from asking questions. – user2357112 Feb 22 '15 at 19:17
  • 1
    [how about just tell yum to accept everything](http://serverfault.com/questions/442088/how-do-you-answer-yes-for-yum-install-automatically) – Antti Haapala -- Слава Україні Feb 22 '15 at 19:21
  • I dont run yum actually, I run `sudo scp -i` for transferring files between two ec2 instances – Sailesh Kotha Feb 22 '15 at 19:23
  • I think it's the passing of yes and no that is at issue here - so this might be a more appropriate duplicate (it suggests using a pipe) - http://stackoverflow.com/questions/26615113/python-fabric-how-to-send-password-and-yes-no-for-user-prompt. However, this also has a good answer below that is not duplicated on that question – J Richard Snape Apr 22 '15 at 15:48

2 Answers2

7

You can use subprocess.Popen and write to stdin, you need the -S flag for sudo then just the rest of the commands.

from subprocess import Popen, PIPE
import getpass

pwd = getpass.getpass()
proc = Popen(['sudo', '-S', rest of commands ],stdout=PIPE, stdin=PIPE, stderr=PIPE,universal_newlines=True)
proc.stdin.write("{}\n".format(pwd))
out,err = proc.communicate(input="{}\n".format("yes"))
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321
1

You can add a pipe and do

yes | os.system("yum install boto")

it will repeat yes until the command is done

elcapitan
  • 145
  • 1
  • 2
  • 13