Reputation: 81
I have a question regarding subprocess.Popen .I'm calling a shell script and provide fewinputs. After few inputs ,I want user running the python script to input.
Is it possible to transfer control from Popen process to command line.
I've added sample scripts
sample.sh
echo "hi"
read input_var
echo "hello" $input_var
read input_var1
echo "Whats up" $input_var1
read input_var2
echo "Tell something else" $input_var2
test.py
import os
from subprocess import Popen, PIPE
p=Popen([path to sample.sh],stdin=PIPE)
#sample.sh prints asks for input
p.stdin.write("a\n")
#Prompts for input
p.stdin.write("nothing much\n")
#After the above statement ,User should be able to prompt input
#Is it possible to transfer control from Popen to command line
Output of the program python test.py
hi
hello a
Whats up b
Tell something else
Please suggest if any alternate methods available to solve this
Upvotes: 2
Views: 4837
Reputation: 3593
As soon as your last write
is executed in your python script, it will exit, and the child shell script will be terminated with it. You request seems to indicate that you would want your child shell script to keep running and keep getting input from the user. If that's the case, then subprocess
might not be the right choice, at least not in this way. On the other hand, if having the python wrapper still running and feeding the input to the shell script is enough, then you can look at something like this:
import os
from subprocess import Popen, PIPE
p=Popen(["./sample.sh"],stdin=PIPE)
#sample.sh prints asks for input
p.stdin.write("a\n")
#Prompts for input
p.stdin.write("nothing much\n")
# read a line from stdin of the python process
# and feed it into the subprocess stdin.
# repeat or loop as needed
line = raw_input()
p.stdin.write(line+'\n')
# p.stdin.flush() # maybe not needed
As many might cringe at this, take it as a starting point. As others have pointed out, stdin/stdout interaction can be challenging with subprocesses, so keep researching.
Upvotes: 4