Sagar
Sagar

Reputation: 59

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

Upvotes: 2

Views: 6547

Answers (3)

Jeremy Davis
Jeremy Davis

Reputation: 750

(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')

Upvotes: 0

Aritesh
Aritesh

Reputation: 2103

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)

Upvotes: 2

Pitto
Pitto

Reputation: 8579

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.

Upvotes: 0

Related Questions