【问题标题】:How can I kill multiple processes at once in python?如何在python中一次杀死多个进程?
【发布时间】:2020-08-09 05:41:15
【问题描述】:

我有一个 python 脚本,负责验证是否存在具有各自名称的进程,我正在使用 pip 模块pgrep,问题是它不允许我使用 kill 模块杀死进程pip 或os.kill 的,因为有几个我想杀死的进程,这些都保存在列表中,例如

pid = [2222, 4444, 6666]

你怎么能一次杀死这些进程?因为上面的模块没有给我结果。

【问题讨论】:

  • 写一个for循环...
  • [os.kill(p,9) for p in pid].. 这将杀死一个又一个 pid..
  • 否 @ArunKalirajaBaskaran - 编写 for 循环 - 请参阅 stackoverflow.com/questions/5753597/…
  • 看起来怎么样?
  • 哦,好吧,我会发布一个答案。等一下……

标签: python pid kill


【解决方案1】:

您将使用for 循环遍历进程。理想情况下,您应该在使用SIGKILL 之前发送SIGTERM,因为它可以让进程更优雅地退出。

import time
import os
import signal

# send all the processes a SIGTERM
for p in pid:
    os.kill(p, signal.SIGTERM)

# give them a short time to do any cleanup
time.sleep(2)

# in case still exist - send them a SIGKILL to definitively remove them
# if they are already exited, just ignore the error and carry on
for p in pid:
    try:
        os.kill(p, signal.SIGKILL)
    except ProcessLookupError:
        pass

【讨论】:

    【解决方案2】:

    试试这个可能有用

    processes = {'pro1', 'pro2', 'pro3'}
    for proc in psutil.process_iter():  
        if proc.name() in processes:
           proc.kill()
    

    更多信息可以参考here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-02-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-07
      相关资源
      最近更新 更多