Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I respond to a prompt in os.system?

I'm trying to do something like this:

from subprocess import Popen
p = Popen(["vagrant", "ssh", "vmname", "-c", '"pvcreate -ff /dev/sdb"'])

But it requires user input. Also, that didn't work anyway. They give the error: bash: pvcreate -ff /dev/sdb: command not found, because it's looking for a program pvcreate -ff /dev/sdb, instead of pvcreate with arguments. I also tried this first:

p = Popen(["vagrant", "ssh", "vmname", "-c", "pvcreate", "-ff", "/dev/sdb"])

And have resorted to using this:

os.system("vagrant ssh vmname -c 'pvcreate -ff /dev/sdb'")

However I need to say yes when it prompts me. I've already tried these options as well:

os.system("yes | vagrant ssh vmname -c 'pvcreate -ff /dev/sdb'")
os.system("echo y | vagrant ssh vmname -c 'pvcreate -ff /dev/sdb'")

Is it possible to respond to a prompt using os.system?

like image 324
rofls Avatar asked Oct 17 '25 02:10

rofls


1 Answers

I'd suggest using the list form of invocation.

import subprocess
command = ["vagrant", "ssh", "vmname", "-c", "pvcreate -ff /db/sdb"]
output,error  = subprocess.Popen(
                command, universal_newlines=True,
                stdout=subprocess.PIPE,  
                stderr=subprocess.PIPE).communicate()

This represents the set of parameters that are going to be passed and eliminates the need to mess around with shell quoting.

like image 198
Jay Avatar answered Oct 19 '25 17:10

Jay