test.py file
#test.py
#!/usr/bin/env python3
while True:
inp = input("input: ")
print("output: " + inp)
subp.py file:
#subp.py
#!/usr/bin/env python3
from subprocess import Popen, PIPE
cmd = Popen(["python3", "test.py"], stdin=PIPE, stdout=PIPE)
while True:
print("Writing to stdin")
cmd.stdin.write("My Input To PIPE")
print("Done Writing to stdin")
print("Reading from stdout")
s = cmd.stdout.readline()
print("Done reading from stdout") # Never executes this line
The output is the following:
Writing to stdin
Done Writing to stdin
Reading from stdout
I understand that the line s = cmd.stdout.readline()
is going to block until EOF
is found in the stdout
file object.
And if I am right, EOF
will never be found in stdout
unless stdout
gets closed ? Can somebody correct me on this?
Going by my understanding, if I modify test.py
import sys
while True:
inp = input("input: ")
print("output: " + inp)
sys.stdout.close() # Added this line hoping to unblock stdout.readline()
Nothing changes, cmd.stdout.readline()
still is looking for EOF
even though the stdout file
is closed ?
What am I missing? I am more concerned about the theory rather done just making it work without understanding. Thank you for the explanations
Also if modify subp.py
and add the line cmd.stdout.close()
before the line s = cmd.stdout.readline()
, it throws an error saying that I tried reading from a closed file object, which makes sense, but how come it did not throw an error when I close the stdout
file object in the test.py
file by adding the line sys.stdout.close()
. Are these two stdout different things?