首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >终止python脚本中的进程及其子进程

终止python脚本中的进程及其子进程
EN

Stack Overflow用户
提问于 2015-12-17 18:09:29
回答 1查看 847关注 0票数 0

在我的脚本中,我得到了一个进程id(parent/main)

对于id为3-4的主进程,有几个子进程在linux终端上运行。

我的需求来自那个process _ and,它也会杀死所有子进程和子进程。

我试过了

代码语言:javascript
复制
 import os
 pid = parent process id
 from  subprocess import call
 call(["pkill", "-TERM","-P", str(pid)])

但在这方面做得并不成功。

也尝试过

代码语言:javascript
复制
 os.system('kill -9 ' + pid)  # only parent is getting killed subpid are still running.

请建议类似于通过主进程id.then in循环列出所有子进程,如何杀死这些子进程,然后是父进程。

kill process and its sub/co-processes by getting their parent pid by python script

遗憾的是,这对我的情况没有帮助。

EN

回答 1

Stack Overflow用户

发布于 2015-12-17 18:32:11

使用psutil可以做到这一点。

代码语言:javascript
复制
import signal
import psutil

def kill(ppid, signal=signal.SIGTERM):
    try:
      process = psutil.Process(ppid)
    except psutil.NoSuchProcess:
      return
    pids = process.get_children(recursive=True)
    for pid in pids:
      os.kill(pid.pid, signal)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34331835

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档