'Python Subprocess to Pass yes / No
I have command which asks for input "YES". How do I pass this answer automatically?
I have used below code and it's not working.
from subprocess import Popen, PIPE
foo_proc = Popen([cmd], stdin=PIPE, stdout=PIPE)
yes_proc = Popen(['YES'], stdout=foo_proc.stdin)
foo_output = foo_proc.communicate()[0]
yes_proc.wait()
Error that I am getting:
echo: write error: Broken pipe
PS: I am using python2.7
Solution 1:[1]
I will suggest to use the simple piped commands directly in Popen statement. You can use the following -
foo_proc = Popen(['echo' , 'yes', '|', cmd])
You need to use shell=True
, e.g.
foo_proc = subprocess.Popen(['echo yes | conda install pyqtgraph'], shell=True)
For more details refer (this link)
Solution 2:[2]
For CLI interaction I would use a Python module for controlling interactive programs in a pseudo-terminal like Pexpect.
It would allow you to perform similar and more complex tasks:
# This connects to the openbsd ftp site and
# downloads the recursive directory listing.
import pexpect
child = pexpect.spawn('ftp ftp.openbsd.org')
child.expect('Name .*: ')
child.sendline('anonymous')
child.expect('Password:')
child.sendline('[email protected]')
child.expect('ftp> ')
child.sendline('lcd /tmp')
child.expect('ftp> ')
child.sendline('cd pub/OpenBSD')
child.expect('ftp> ')
child.sendline('get README')
child.expect('ftp> ')
child.sendline('bye')
You can find its documentation here.
Solution 3:[3]
(Note this is python3 - python2 is EOL)
Just pass the 'YES' into communicate (don't forget the newline).
from subprocess import Popen, PIPE
foo_proc = Popen([cmd], stdin=PIPE, stdout=PIPE, text=True)
foo_proc.communicate('YES\n')
If you'd rather use byte-strings, remove text=True
and prefix b
to the string within communicate. I.e.:
foo_proc = Popen([cmd], stdin=PIPE, stdout=PIPE)
foo_proc.communicate(b'YES\n')
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | rrao |
Solution 2 | Pitto |
Solution 3 | Jeremy Davis |