1

I am trying to code a Python script that will execute another script and then interact with that script. By "interact" I mean send and receive input.

Here is how it should flow:

Script1 executes Script2 and waits for input from Script2.

Script1 receives input from Script 2 then sends back output to Script2.

This is repeated 2 or more times.

Lastly, I would like the whole process to be visible in the shell.

Here is the code I am feverishly trying to get to work:

import subprocess
from subprocess import Popen, PIPE, STDOUT

output1 = '1234'
output2 = '12345'
output3 = '123456'

p = subprocess.Popen(['receiver.py'], shell=True, stdout=subprocess.PIPE, stdin=subprocess.PIPE)

input1 = p.stdin.read()
print(input1)
p.stdin.write(output1)
p.communicate()[0]

input2 = p.stdin.read()
print(input2)
p.stdin.write(output2)
p.communicate()[0]

input3 = p.stdin.read()
print(input3)
p.stdin.write(output3)
p.communicate()[0]

p.stdin.close()
p.stdout.close()

quit()
8
  • 1
    Got a summary of what is happening, since you have told us what you expect? Commented Dec 30, 2019 at 21:43
  • Can you explain what you mean by "process to be visible in the shell"? That could be anything from printing to sys.stdout to making subprocess calls in shell. On the other had, this sounds like a great application for concurrent programming with asyncio or at least a "manager" for both scripts that can handle their interplay. Commented Dec 30, 2019 at 21:46
  • @SunnyPatel The current error I am receiving is: ``` File "receiver.py", line 4, in <module> input1 = input('First input line to receive.\n') EOFError: EOF when reading a line close failed in file object destructor: sys.excepthook is missing lost sys.stderr``` Commented Dec 30, 2019 at 21:48
  • @BrianJoseph I will execute the first script in a Terminal, so I would like to see the input and output as printed lines in the terminal. Commented Dec 30, 2019 at 21:50
  • 1
    You'll want to do your reading from p.stdout, and writing to p.stdin Commented Dec 30, 2019 at 22:56

0

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.