Reputation: 279
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
Upvotes: 4
Views: 7677
Reputation: 48047
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))
Upvotes: 7
Reputation: 87054
Actually the subprocess does work - but you are not seeing the prompts because the standard out of the child process is being captured by proc.communicate()
. You can confirm this by entering values for the 3 prompts and you should finally see the prompts and your input echoed.
Just remove the stdout=subprocess.PIPE
(same for stderr) and the subprocess' stdout (stderr) will go to the terminal.
Or there are other functions that will start a subprocess and call communicate()
for you, such as subprocess.call()
or subprocess.check_call()
Upvotes: 2