I have a subprocess that either quits with a returncode, or asks something and waits for user input.
I would like to detect when the process asks the question and quit i
My idea to find out if the subprocess reads user input is to (ab)use the fact that file objects are stateful: if the process reads data from its stdin, we should be able to detect a change in the stdin's state.
The procedure is as follows:
This is the code:
import os
import time
import tempfile
import subprocess
# create a file that we can use as the stdin for the subprocess
with tempfile.TemporaryFile() as proc_stdin:
# write some data to the file for the subprocess to read
proc_stdin.write(b'whatever\r\n')
proc_stdin.seek(0)
# start the thing
cmd = ["python","ask.py"]
proc = subprocess.Popen(cmd, stdin=proc_stdin, stdout=subprocess.PIPE)
# wait for it to start up and do its thing
time.sleep(1)
# now check if the subprocess read any data from the file
if proc_stdin.tell() == 0:
print("it didn't take input")
else:
print("it took input")
Ideally the temporary file could be replaced by some kind of pipe or something that doesn't write any data to disk, but unfortunately I couldn't find a way to make it work without a real on-disk file.