Provide a shell script with a name in Python

I have a python program that uses various Bash shell scripts. However, some of them require input (y / n). I know that the input signal is needed based on the question number, so it can automatically provide this.

Is there a way in Python for this?

As a last resort, I can send a signal to a window, etc., but I would prefer not to.

+2
source share
2 answers

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

import pexpect child = pexpect.spawn('ftp ftp.openbsd.org') child.expect('Name .*: ') child.sendline('anonymous') child.expect('Password:') child.sendline(' noah@example.com ') child.expect('ftp> ') child.sendline('cd pub') child.expect('ftp> ') child.sendline('get ls-lR.gz') child.expect('ftp> ') child.sendline('bye') 

If you do not want to use the add-on module, using subprocess.Popen is the way to go, but it is more complicated. First you create a process.

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

Here you can use shell=True or add the shell name to the command arguments. The first is simpler.

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

+2
source

Use subprocess.Popen .

 from subprocess import Popen, PIPE popen = Popen(command, stdin=PIPE) popen.communicate('y') 
+3
source

All Articles