通过python脚本

时间:2015-11-26 06:45:20

标签: python python-multiprocessing kill-process

我正在使用MULTIPROCESSING来查找我的要求。 当它运行时,我得到一个pid(可能是父母!我不知道该怎么称呼)然后用他们自己的pid和第一个进程的引用ID进行处理。

现在我需要通过杀死第一个过程来杀死所有这些过程,这将是最好的方法。这也是PYTHONIC方式。

场景就像

  ps -ef |grep py

我正在

  2222 0001 first.py  #0001 is os process
  4323 2222 second.py
  4324 2222 third.cgi
  4324 2222 fourth.py
  4325 2222 fifth.cgi
  4326 2222 sixth.py

  2223 0001 newfirst.py    ############new first process from another script started
  4327 2223 newsecond.cgi
  4328 2223 newthird.py
  4329 2223 newfourth.cgi

现在我正在通过(当按下停止按钮时)杀死进程

 kill -6 2222   ###from terminal

然后只有first.py被杀死,其余的协同进程仍在运行。当然我可以从终端中杀死其他进程,但是我想以更加pythonic的方式执行它(通过运行一个脚本,当有人按下STOP按钮从前端设计运行.py文件时会触发)

现在我怎么能在我杀死first.py时杀死所有这些共同进程(因为我不想让它的伙伴再次运行)但是另一个newfirst.py及其co&# 39; s不应该被打扰。

我到目前为止是什么

import os
pid = os.getpid()   
os.system('kill -9 ' + pid)

所以如何从第一个进程id 2222过滤掉共同进程并杀死它们。

我也尝试过使用psutil,但是在名字后面传递名字来杀人并不是很有说服力。

我已经检查过subprocess.popen方法但是失败了,现在我没有逻辑,请建议。

如果需要任何其他信息,请发表评论。

1 个答案:

答案 0 :(得分:1)

从你的问题来看,我无法理解;但是我假设你有方便的工具id,例如在您的示例中,您有进程ID 2222.然后您可以尝试:

#Assuming you have parent_pid i.e. from your example you have 2222
pname = psutil.Process(parent_pid)
cpid = pname.get_children(recursive=True)
for pid in cpid:
    os.kill(pid.pid, signal_num) #signal_num is the signal you want to send i.e. 9 as per your example

请注意例外处理,例如使用try - except块检查进程/子进程是否存在,然后再使用$data = array ( 'productname'=>array(0=>7, 1=>8), 'quantity'=>array(0=>23, 1=>22), 'price'=>array(0=>2, 1=>2), 'subtotal'=>array(0=>46, 1=>44), ); $result = array(); foreach($data as $key => $value) { foreach($value as $s_key => $s_value) { $result[$s_key][$key] = $s_value; } } var_dump($result); 阻止它。