A couple notes:

-I think the Python interpreter actually sends its output to stderr, so to 
capture it you'd probably want it to go to the same place as stdout, so use 
stderr = subprocess.STDOUT

-You're only reading 1 line out output for each thing, so if 1 command creates 
multiple lines of output then you won't be showing them all.

-You're never actually checking if the called process is still alive or not. It 
should normally be something like:
...
interpreter = subprocess.Popen(...)
...
interpreter.poll()
while interpreter.returncode is not None:
    ...
    interpreter.poll()
cleanup stuff

-To the actual question it looks like it has the stdout stream in blocking mode 
somehow. So when you're reading from stdout and there's nothing there it's 
blocking and waiting for there to be something, which will never happen. 
Flipping through the documentation for subprocess, and io (interpreter.stdout 
is of <class '_io.BufferedReader'>) io mentions blocking vs non blocking a lot, 
but it's not mentioned in subprocess. And I don't see in either how to tell if 
a stream is in blocking mode or not, or how or if it's possible to change that. 
So I don't know what to suggest for that, sorry.

-----Original Message-----
From: Python-list 
[mailto:python-list-bounces+david.raymond=tomtom....@python.org] On Behalf Of 
cseber...@gmail.com
Sent: Wednesday, August 01, 2018 4:11 PM
To: python-list@python.org
Subject: Dealing with errors in interactive subprocess running python 
interpreter that freeze the process

I can run python3 interactively in a subprocess w/ Popen but
if I sent it text, that throws an exception, the process freezes
instead of just printing the exception like the normal interpreter..
why? how fix?  Here is my code below.

(I suspect when there is an exception, there is NO output to stdin so that
the problem is the line below that tries to read from stdin never finishes.
Maybe I need a different readline that can "survive" when there is no output 
and won't block?)

....

import subprocess
 
interpreter = subprocess.Popen(['python3', '-i'],
                               stdin  = subprocess.PIPE,
                               stdout = subprocess.PIPE,
                               stderr = subprocess.PIPE)
 
while True:
        exp = input(">>> ").encode() + b"\n"
        interpreter.stdin.write(exp)
        interpreter.stdin.flush()
        print(interpreter.stdout.readline().strip())
interpreter.stdin.close()
interpreter.terminate()
-- 
https://mail.python.org/mailman/listinfo/python-list
-- 
https://mail.python.org/mailman/listinfo/python-list

Reply via email to