I'm writing a Python 3.6 program on Windows to record all the input to a subprocess for backup. (I cannot modify the subprocess code as the real program is a commercial product (exe file) and I don't have the source code.)
I tried the following code, and it doesn't work. The text only shows in the terminal, and the txt files used for logging are empty.
Main.py:
import subprocess
import sys
class dup_stream():
def __init__(self, original_stream, file):
self.original_stream = original_stream
self.log = open(file, 'a')
def write(self, message):
self.log.write(message)
self.original_stream.write(message)
def fileno(self):
return self.original_stream.fileno()
completed_process = subprocess.run('python Hello.py',
stdin=dup_stream(sys.stdin, 'stdin.txt'),
stderr=dup_stream(sys.stderr, 'stderr.txt'),
stdout=dup_stream(sys.stdout, 'stdout.txt'))
Hello.py:
name = input("Your name:") # e.g. "Jane Doe"
print('Hello,',name)
Expected result:
In terminal:
Your name: Jane Doe
Hello, Jane Doe
stdin.txt:
Jane Doe
stdout.txt:
Your name:
Hello, Jane Doe
I've asked a more general question before (Capture inputs to subprocess.run()), but there aren't any practical answer.