Praneeth Praneeth - 1 year ago 71
Bash Question

Executing Interactive shell script in python

I have a shell script with ask for the user input. Consider a below example

echo -n "Enter name > "
read text
echo "You entered: $text"
echo -n "Enter age > "
read text
echo "You entered: $text"
echo -n "Enter location > "
read text
echo "You entered: $text"

Script Execution:

Enter name> abc
You entered: abc
Enter age > 35
You entered: 35
Enter location > prop
You entered: prop

Now i called this script in python program. I am doing this using sub process module. As far as i know sub process module creates a new process. The problem is when i execute the python script i am not able to pass the parameters to underlying shell script and the scipt is in hault stage. Could some point me where i am doing wrong

python script (CHECK.PY):

import subprocess, shlex

cmd = "sh"
proc = subprocess.Popen(shlex.split(cmd), stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout,stderr = proc.communicate()

print stdout

Python Execution:


Answer Source

Your code is working, but since you mention stdout=subprocess.PIPE the content is going to stdout variable you defined in stdout,stderr = proc.communicate(). Remove stdout=subprocess.PIPE argument from your Popen() call and you will see the output.

Alternatively, you should be using subprocess.check_call() as:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download