In python 3 (on Linux or MacOSX10.8) how can I get a parent process to read just a prompt (that does not include \n) issued by a subprocess, not the entire buffer till \n?
# program names.py
print("I am Joe.") #1print
name = input("What is your name? ") #2prompt
print("Hi", name, "!") #3print
# program parent.py (in python 3.3.0)
import subprocess
import sys
p = subprocess.Popen([sys.executable, "names.py"],
bufsize=0,
stdin =subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=False,
universal_newlines=True
)
print(p.stdout.readline(), end='')
p.stdin.write("Sue\n")
# The next print will produce the output of 2prompt + 3print:
print(p.stdout.readline(), end='')
When I run parent.py it prints:
I am Joe.
What is your name? Hi Sue !
How to modify parent.py so that it prints:
I am Joe.
What is your name?
Hi Sue !
That is, how to extract separately the output produced by prompt and print?
readline() reads from names.py until the next \n, where what you need is a "read as much as there is right now". Time is an additional factor here, since you basically have to detect, when names.py is waiting (expecting input).
Basically, you need a read()-operation with a timeout. You could start a separate thread that reads from names.py byte by byte into a buffer. You can then join(timeout) this thread and access its buffer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With