elcapitan
elcapitan

Reputation: 155

Python subprocess command answering prompt

I am trying to call a command

ionic cordova prepare

which prompts for a "Y/N" response. I always want this to be yes. When i tried using os.system it would hang at the last part and not move onto the rest of the script. Does anyone know the right way of writing this.

This is what i tried

foo_proc = Popen(['ionic', 'cordova', 'prepare'], stdin=PIPE, stdout=PIPE)
yes_proc = Popen(['yes', 'y'], stdout=foo_proc.stdin)
foo_proc.communicate()[0]
yes_proc.wait()

But it just hangs on the command and doesn't seem to execute

Upvotes: 2

Views: 13689

Answers (4)

FlorenceMei
FlorenceMei

Reputation: 11

I also had problems with communicating several Y/N/ to answer a script launched with subprocess... Nothing worked, I did not find any good 'clean' solution in the end, so I used a trick: I created a bash script (launch_script.sh) where I wrote:

echo -e "Y\nN\nY\n" | scripttoanswer.ksh

in it and then used subprocess to simply launch it:

subprocess.run(["/home/user/dev/my_project/launch_script.sh"], shell=True)

Upvotes: 1

medley56
medley56

Reputation: 1378

As of python 3.5, the subprocess module introduced the high level run method, which returns a CompletedProcess object:

subprocess.run(['somecommand', 'somearg'], capture_output=True, text=True, input="y")

See documentation here

Upvotes: 5

tz01x
tz01x

Reputation: 43

This work for me:

foo_proc = Popen(['ionic', 'cordova', 'prepare'], stdin=PIPE, stdout=PIPE)
foo_proc.stdin.write(b"y\n")
outputlog, errorlog = foo_proc.communicate()
foo_proc.stdin.close()

Upvotes: 2

pankaj mishra
pankaj mishra

Reputation: 2615

Agree with Charles duffy example here,May be this can help you!!

from subprocess import Popen,PIPE
foo_proc = Popen(['ionic', 'cordova', 'prepare'], stdin=PIPE, stdout=PIPE)
foo_proc.communicate(input='y')

Upvotes: 0

Related Questions