pythonlinuxpython-2.7os.system

Give response yes/no in python when a command is executed os.system() in python linux


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?


Solution

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