Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Provide called shell script with input in Python

I have a python program which uses various Bash shell scripts. However, some of them require (y/n) input. I know the input required based on the question number so it's a matter of being able to provide that automatically.

Is there a way in Python to do that?

As a last resort I can send a signal to a window etc. but I'd rather not do that.

like image 590
s5s Avatar asked Jan 19 '26 02:01

s5s


2 Answers

Probably the the easiest way is to use pexpect. An example (from the overview in the wiki):

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('cd pub')
child.expect('ftp> ')
child.sendline('get ls-lR.gz')
child.expect('ftp> ')
child.sendline('bye')

If you don't want to use an extra module, using subprocess.Popen is the way to go, but it is more complicated. First you create the process.

import subprocess

script = subprocess.Popen(['script.sh'], stdin=subprocess.PIPE,
                          stdout=subprocess.PIPE, shell=True)

You can either use shell=True here, or prepend the name of the shell to the command arguments. The former is easier.

Next you need to read from script.stdout until you find your question number. Then you write the answer to script.stdin.

like image 64
Roland Smith Avatar answered Jan 21 '26 17:01

Roland Smith


Use subprocess.Popen.

from subprocess import Popen, PIPE


popen = Popen(command, stdin=PIPE)
popen.communicate('y')
like image 41
pydsigner Avatar answered Jan 21 '26 17:01

pydsigner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!