kill subprocess when python process is killed?

后端 未结 3 530
自闭症患者
自闭症患者 2021-01-05 17:17

I am writing a python program that lauches a subprocess (using Popen). I am reading stdout of the subprocess, doing some filtering, and writing to stdout of main process.

相关标签:
3条回答
  • 2021-01-05 17:49

    Windows doesn't have signals, so you can't use the signal module. However, you can still catch the KeyboardInterrupt exception when Ctrl-C is pressed.

    Something like this should get you going:

    import subprocess
    
    try:
        child = subprocess.Popen(blah)
        child.wait() 
    
    except KeyboardInterrupt:
        child.terminate()
    
    0 讨论(0)
  • 2021-01-05 18:02

    You can use python atexit module.

    For example:

    import atexit
    
    def killSubprocess():
        mySubprocess.kill()
    
    atexit.register(killSubprocess)
    
    0 讨论(0)
  • 2021-01-05 18:08

    subprocess.Popen objects come with a kill and a terminate method (differs in which signal you send to the process).

    signal.signal allows you install signal handlers, in which you can call the child's kill method.

    0 讨论(0)
提交回复
热议问题