0
votes

I have an executable which takes a lot of input. I would like to call a python script which will run the executable, pass some input, then gracefully exit while the shell inherits the child process, with the normal stdin/stdout/stderr setup so that it may continue passing input.

Simple consumer input.sh:

#/bin/bash

echo "expected input: abc"
read in1
if [ "$in1" != "abc" ]; then
  echo "wrong!"
  exit 1
fi

echo "expected: def"
read in2
if [ "$in2" != "def" ]; then
  echo "wrong!"
  exit 1
fi

echo "SUCCESS!"

The intermediate python script:

#!/usr/bin/python
import sys
import subprocess

proc = subprocess.Popen('/Users/myuser/input.sh', shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE)

out = proc.stdout.readline()
if "expected input: abc" in out:
  proc.stdin.write("abc\n")

  out = proc.stdout.readline()
  if "expected input: def" in out:
    print "my job is done here, you take over"
    # MAGIC HERE! redirect proc streams to parent and exit gracefully
  else:
    print "error"
else:
  print "error"
  1. User, on the bash shell, executes the above python script
  2. Python script executes input.sh
  3. Python script passes "abc" to input.sh stdin when it sees the correct prompt
  4. Python script does aforementioned MAGIC and exits
  5. input.sh is inherited by the bash shell, stdin/stdout/stderr and all
  6. User now sees the stdout from input.sh and can enter "def" on stdin to finally receive "SUCCESS!" and exit code 0.

I may be overthinking it but I have no idea how to gracefully exit from the python script ensuring the stdin/stdout/stderr from input.sh replaces that of the Python script. In this scenario the Python script is simply an intermediary which is supposed to make the user's life easier by answering some prompts for him or her and relinquishing control at a later stage.

1
Why bother with all these hops? Why not just use Python all the time? - John Zwinck
For something this small it seems like actual shell, perhaps sprinkled with the appropriate call to 'nohup' might be simpler. - pvg
I appreciate the suggestion but in reality the shell script is long, complex, and takes a lot of input. The shell and python scripts above are just supposed to illustrate the issue, thus they are simple. - pystumped

1 Answers

0
votes

You can use Popen.communicate to send and receive data to/from child process. https://docs.python.org/3.6/library/subprocess.html#subprocess.Popen.communicate