How do I close the stdout-pipe when killing a process started with python subprocess Popen?

后端 未结 3 1535
臣服心动
臣服心动 2021-02-06 03:18

I wonder if it is possible to shut down the communication pipe when killing a subprocess started in a different thread. If I do not call communicate() then kill() will work as e

3条回答
  •  一个人的身影
    2021-02-06 03:41

    It looks like you may be a victim of Python's super coarse grained concurrency. Change your script to this:

    #!/bin/bash
    echo "sleeping five"
    sleep 5
    echo "sleeping five again"
    sleep 5
    echo "slept five"
    

    And then the output becomes:

    process: sleeping five
    
    real    0m5.134s
    user    0m0.000s
    sys     0m0.010s
    

    If the entire script ran, the time would be 10s. So it looks like the python control thread doesn't actually run until after the bash script sleeps. Similarly, if you change your script to this:

    #!/bin/bash
    echo "sleeping five"
    sleep 1
    sleep 1
    sleep 1
    sleep 1
    sleep 1
    echo "slept five"
    

    Then the output becomes:

    process: sleeping five
    
    real    0m1.150s
    user    0m0.010s
    sys     0m0.020s
    

    In short, your code works as logically implemented. :)

提交回复
热议问题