4

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
1
  • We can perform the same thing using OS module, But i am trying to achieve using subprocess module Commented Oct 5, 2016 at 11:05

2 Answers 2

7

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))
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for the answer. How can we capture the output of that script? I am having python 2.6.6
If you will capture the output, you would not be able to see the content of printed by your script on the console. Is that what you want? For that you may use subprocess.check_output()
Check_output works fine.. I tested.. But i need to use python 2.6.6
Thanks for the answer - is there a way to make this work in Jupyter. It works fine in command line but not on Jupyter!
2

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()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.