Proper way of re-using and closing a subprocess object

后端 未结 4 729
猫巷女王i
猫巷女王i 2021-01-12 18:56

I have the following code in a loop:

while true:
    # Define shell_command
    p1 = Popen(shell_command, shell=shell_type, stdout=PIPE, stderr=PIPE, preexec         


        
4条回答
  •  抹茶落季
    2021-01-12 19:32

    The "correct" order is:

    1. Create a thread to read stdout (and a second one to read stderr, unless you merged them into one).

    2. Write commands to be executed by the child to stdin. If you're not reading stdout at the same time, writing to stdin can block.

    3. Close stdin (this is the signal for the child that it can now terminate by itself whenever it is done)

    4. When stdout returns EOF, the child has terminated. Note that you need to synchronize the stdout reader thread and your main thread.

    5. call wait() to see if there was a problem and to clean up the child process

    If you need to stop the child process for any reason (maybe the user wants to quit), then you can:

    1. Close stdin if the child terminates when it reads EOF.

    2. Kill the with terminate(). This is the correct solution for child processes which ignore stdin.

    3. If the child doesn't respond, try kill()

    In all three cases, you must call wait() to clean up the dead child process.

提交回复
热议问题