Killing a subprocess exits Python program

2020-05-01 09:25发布

def playvid(self):
    proc1 = subprocess.Popen("gst-launch-1.0 videotestsrc ! autovideosink", shell=True)
    time.sleep(3)
    os.killpg(os.getpgid(proc1.pid),signal.SIGTERM)

This function gets called when I press a button (created using TK library). After 3 seconds my entire program (along with the GUI screen) gets killed instead of only the subprocess. How do I rectify this and make sure that only the subprocess proc1 is killed.

1条回答
▲ chillily
2楼-- · 2020-05-01 09:55

If you read the documentation for subprocess there are several methods to choose from:

Popen.send_signal(signal)

Sends the signal signal to the child.

On Windows, SIGTERM is an alias for terminate().

Popen.terminate()

Stop the child. On Posix OSs the method sends SIGTERM to the child. On Windows the Win32 API function TerminateProcess() is called to stop the child.

Popen.kill()

Kills the child. On Posix OSs the function sends SIGKILL to the child. On Windows kill() is an alias for terminate().

I would use:

proc1.terminate()
查看更多
登录 后发表回答