Proper way of re-using and closing a subprocess object

后端 未结 4 775
猫巷女王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:52

    1. Depends on what you expect the process to do; you should always call p1.wait() in order to avoid zombies. Other steps depend on the behaviour of the subprocess; if it produces any output, you should consume the output (e.g. p1.read() ...but this would eat lots of memory) and only then call the p1.wait(); or you may wait for some timeout and call p1.terminate() to kill the process if you think it doesn't work as expected, and possible call p1.wait() to clean the zombie.

    Alternatively, p1.communicate(...) would do the handling if io and waiting for you (not the killing).

    1. Subprocess objects aren't supposed to be reused.

提交回复
热议问题