Since input and raw_input() stop the program from running anymore, I want to use a subprocess to run this program…
while True: print raw_input()
and get its output.
This is what I have as my reading program:
import subprocess
process = subprocess.Popen('python subinput.py', stdout=subprocess.PIPE, stderr=subprocess.PIPE)
while True:
output=process.stdout.read(12)
if output=='' and process.poll()!=None:
break
if output!='':
sys.stdout.write(output)
sys.stdout.flush()
When I run this, the subprocess exits almost as fast as it started. How can I fix this?
I’m afraid it won’t work this way.
You assume, that
subprocesswill attach your console (your specialcase of
stdin). This does not work, the module only has twooptions for specifying that:
PIPEandSTDOUT.When nothing is specified, the subprocess won’t be able to use
the corresponding stream – it’s output will go nowhere or it will
receive no input. The
raw_input()ends because of EOF.The way to go is to have your input in the “main” program,
and the work done in a subprocess.
EDIT:
Here’s an example in
multiprocessingYou of course need to make it more robust by finding a way too stop
this cooperation. In my example both processes are in the same file,
but you may organize it differently.
This example works on Linux, you may have some problems with pipes on Windows,
but it should be altogether solvable.
The “Processing” is the part where you want to do something else, not just
wait for the data from the parent.