Hi,

I am trying to invoke a shell script from python.

This shell script while running expects user inputs based on which it proceeds to perform several actions.

I want to automate the process of sending the user inputs(may be from a file)

I am using the subprocess Popen class to invoke the script and then the Popen.communicate method to pass the user inputs.

The communicate method only passes the first input and the next set of inputs are not passed

Can anyone please guide me further on this

Example script

# Shell Script Ex.sh
PASS="password"
PIN="123"
read -s -p "Password: " mypwd
echo ""
[ "$mypwd" == "$PASS" ] && echo "Password accepted" || echo "Access Denied"
read -s -p "PIN: " mypin
echo ""
[ "$mypin" == "$PIN" ] && echo "PIN accepted" || echo "PIN mismatch"
#python script
import os
from subprocess import Popen, PIPE

proc=Popen('./Ex.sh',stdin=PIPE)
proc.communicate('password')
proc.communicate('123')

The communicate method "reads all of the output and waits for child process to exit before returning" [ Source ], so in order to work with a program that expects multiple inputs you'll need to communicate with the stdin of the process as such:

proc = Popen('./Ex.sh', shell=True, stdin=PIPE, stdout=PIPE)
proc.stdout.readline()
proc.stdin.write('password\n')
proc.stdout.readline()
proc.stdin.write('123\n')
proc.stdout.readline()
...etc

I think it'd be more efficient to let Python poll the user for input and then pass those as parameters to a shell script.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.