How to detect when subprocess asks for input in Windows

后端 未结 2 1274
名媛妹妹
名媛妹妹 2021-02-20 17:12

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

2条回答
  •  无人共我
    2021-02-20 18:00

    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:

    1. Create a temporary file that'll be used as the subprocess's stdin
    2. Write some data to the file
    3. Start the process
    4. Wait a little while for the process to read the data (or not), then use the tell() method to find out if anything has been read from the file

    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.

提交回复
热议问题