Kill a running subprocess call

后端 未结 5 1457
情歌与酒
情歌与酒 2020-11-28 12:08

I\'m launching a program with subprocess on Python.

In some cases the program may freeze. This is out of my control. The only thing I can do from the co

5条回答
  •  难免孤独
    2020-11-28 12:42

    You can use two signals to kill a running subprocess call i.e., signal.SIGTERM and signal.SIGKILL; for example

    import subprocess
    import os
    import signal
    import time
    ..
    process = subprocess.Popen(..)
    ..
    # killing all processes in the group
    os.killpg(process.pid, signal.SIGTERM)
    time.sleep(2)
    if process.poll() is None:  # Force kill if process is still alive
        time.sleep(3)
        os.killpg(process.pid, signal.SIGKILL)
    

提交回复
热议问题