Give response yes/no in python when a command is e

2020-07-31 05:19发布

问题:

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?

回答1:

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"))


回答2:

You can add a pipe and do

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

it will repeat yes until the command is done