Dealing with errors in interactive subprocess running python interpreter that freeze the process

cseberino at gmail.com cseberino at gmail.com
Wed Aug 1 16:11:10 EDT 2018


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()



More information about the Python-list mailing list