I have an interactive command line exe file on Windows, wrote by someone else. When the program has an exception, it terminates and all my inputs to the program are lost.
So I'm writing a python program that calls a blocking subprocess with subprocess.run()
and captures all inputs to stdin
for backup, without affecting the interaction to the subprocess. But I didn't find a way to capture the inputs. How do I do this in Python?
An example (but not working) code would be like:
import subprocess
process = subprocess.run(['program.exe'], stderr = subprocess.PIPE,text=True)
# Interact with the program. Wait for it to finish.
if subprocess_object.returncode != 0:
open('input_backup.txt','w').write(process.stdin) # Won't work
open('error_backup.txt','w').write(process.stderr)
One idea I had is to override an StringIO
object and give it two stream, one sys.stdin
and one file stream to write()
to. Then assign sys.stdin to a instance of that overrided class. But I didn't find a way to do it.