Executing Interactive shell script in python
<p>I have a shell script with ask for the user input. Consider a below example</p>

<p>Test.sh</p>

<pre><code>#!/bin/bash
echo -n "Enter name &gt; "
read text
echo "You entered: $text"
echo -n "Enter age &gt; "
read text
echo "You entered: $text"
echo -n "Enter location &gt; "
read text
echo "You entered: $text"
</code></pre>

<p>Script Execution:</p>

<pre><code>sh test.sh
Enter name&gt; abc
You entered: abc
Enter age &gt; 35
You entered: 35
Enter location &gt; prop
You entered: prop
</code></pre>

<p><em>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</em></p>

<p>python script (CHECK.PY):</p>

<pre><code>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
</code></pre>

<p>Python Execution: check.py</p>

<pre><code> python check.py
</code></pre>

<p>Actually the subprocess does work - but you are not seeing the prompts because the standard out of the child process is being captured by <code>proc.communicate()</code>. You can confirm this by entering values for the 3 prompts and you should finally see the prompts and your input echoed.</p>

<p>Just remove the <code>stdout=subprocess.PIPE</code> (same for stderr) and the subprocess' stdout (stderr) will go to the terminal.</p>

<p>Or there are other functions that will start a subprocess and call <code>communicate()</code> for you, such as <a href="https://docs.python.org/2/library/subprocess.html#subprocess.call" rel="nofollow"><code>subprocess.call()</code></a> or <a href="https://docs.python.org/2/library/subprocess.html#subprocess.check_call" rel="nofollow"><code>subprocess.check_call()</code></a></p>

python python-2.7 shell python-3.x