code.InteractiveConsole.interact() closes stdin on exit, which can be very surprising to successive code, not least future calls to interact(). A simple repro with a workaround is:
import code
import io
import os
import sys
def run():
print(sys.stdin.buffer.raw)
dupstdin = os.dup(0)
try:
code.InteractiveConsole().interact()
except SystemExit:
pass
finally:
# Workaround: Without this line, the second call to run() will fail with a ValueError when
# it tries to call input().
sys.stdin = io.TextIOWrapper(
io.BufferedReader(io.FileIO(dupstdin, mode='rb', closefd=False)),
encoding='utf8')
run()
run()
- The exciting behavior appears to happen inside the exec() of a 'quit()' command, and I haven't searched it out further.
- That behavior inside exec() is likely there for a good reason, in which case the best fix is probably to just save and restore stdin in the code library. |