杀死一个子进程退出 Python 程序 [英] Killing a subprocess exits Python program

查看:38
本文介绍了杀死一个子进程退出 Python 程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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)

当我按下按钮(使用 TK 库创建)时会调用此函数.3 秒后,我的整个程序(以及 GUI 屏幕)被杀死,而不仅仅是子进程.我如何纠正这个问题并确保只有子进程 proc1 被杀死.

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.

推荐答案

如果你阅读了 subprocess 有几种方法可供选择:

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

Popen.send_signal(信号)

向孩子发送信号信号.

在 Windows 上,SIGTERM 是 terminate() 的别名.

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

Popen.terminate()

阻止孩子.在 Posix 操作系统上,该方法将 SIGTERM 发送给孩子.在 Windows 上,调用 Win32 API 函数 TerminateProcess() 来停止子进程.

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()

杀死孩子.在 Posix 操作系统上,该函数向子进程发送 SIGKILL.在 Windows 上,kill() 是 terminate() 的别名.

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

我会使用:

proc1.terminate()

这篇关于杀死一个子进程退出 Python 程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆