Praneeth Praneeth - 2 months ago 8
Bash Question

Executing Interactive shell script in python

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

Test.sh

#!/bin/bash
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:

sh test.sh
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 test.sh"
proc = subprocess.Popen(shlex.split(cmd), stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout,stderr = proc.communicate()

print stdout


Python Execution: check.py

python check.py

Answer

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:

subprocess.check_call(shlex.split(cmd))