Kill a running subprocess call

后端 未结 5 1454
情歌与酒
情歌与酒 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:55

    Well, there are a couple of methods on the object returned by subprocess.Popen() which may be of use: Popen.terminate() and Popen.kill(), which send a SIGTERM and SIGKILL respectively.

    For example...

    import subprocess
    import time
    
    process = subprocess.Popen(cmd, shell=True)
    time.sleep(5)
    process.terminate()
    

    ...would terminate the process after five seconds.

    Or you can use os.kill() to send other signals, like SIGINT to simulate CTRL-C, with...

    import subprocess
    import time
    import os
    import signal
    
    process = subprocess.Popen(cmd, shell=True)
    time.sleep(5)
    os.kill(process.pid, signal.SIGINT)
    

提交回复
热议问题