I encountered a problem in work. Here it is.
I have several scripts(mostly are shell scripts) to execute, and I want to write a python script to run them automatically. One of these shell scripts needs interactive input during it's execution. What troubled me is that I can't find a way to read its input prompt, so I can't decide what to enter to continue.
I simplified the problem to something like this:
There is a script named mediator.py
, which run greeter.sh
inside. The mediator
takes greeter
's input prompt and print it to the user, then gets user's input and pass it to greeter
. The mediator
needs to act exactly the same as the greeter
from user's point of view.
Here is greeter.sh
:
#! /bin/bash
echo "Please enter your name: " # <- I want 'mediator.py' to read this prompt and show it to me, and then get what I input, then pass my input to 'greeter.sh'
read name
echo "Hello, " $name
I want to do this in the following order:
- The user (that's me) run
mediator.py
- The
mediator
rungreeter.sh
inside - The
mediator
get the input prompt ofgreeter
, and output it on the screen.(At this time, thegreeter
is waiting for user's input. This is the main problem I stuck with) - The user input a string (for example, 'Mike'),
mediator
get the string 'Mike' and transmit it togreeter
- The
greeter
get the name 'Mike', and print a greeting - The
mediator
get the greeting, and output it on the screen.
I searched for some solution and determined to use Popen
function in subprocess
module with stdout
of sub-process directed to PIPE
, it's something like this:
sb = subprocess.Popen(['sh', 'greeter.sh'], stdout = subprocess.PIPE, stdin = stdout, stderr = stdout)
but I can't solve the main problem in step 3 above. Can anyone give me some advice for help? Thanks very much!