【问题标题】:how to kill all subprocess in python [closed]如何杀死python中的所有子进程[关闭]
【发布时间】:2013-05-03 18:01:49
【问题描述】:

在 python 中,我打开了 4 个子进程。现在我想在 python 脚本中出现新请求时杀死所有以前的进程。

我正在使用 python 2.7 和 windows 7 操作系统。

谢谢,

【问题讨论】:

  • 你是如何产生这 4 个子进程的,到目前为止你有什么尝试?
  • 其实我的目标是当有新的请求来处理进程时,需要停止以前的进程。
  • 什么是调度子进程?如果您想杀死以前的进程,这些进程的发起者(所有者)将拥有杀死它们所必需的信息。
  • 例如我有两个进程, p = subprocess.Popen("echo t |", shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) p1 = subprocess.Popen([svn, "list ", "-R", Url], shell=True, stdin=p.stdout, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate() ,现在我需要终止这两个进程,当新请求到来时.
  • 请将该代码格式化为您的问题。在评论和重要信息中真的很难阅读。

标签: python windows subprocess popen


【解决方案1】:

假设您想杀死所有子进程而不跟踪它们,外部库 psutil 使这很容易:

   import os
   import psutil
   # spawn some child processes we can kill later
   for i in xrange(4): psutil.Popen('sleep 60')

   # now kill them
   me = psutil.Process(os.getpid())
   for child in me.get_children():
       child.kill()

【讨论】:

  • 当我使用此代码时,我收到错误:WindowsError: [错误 32] 该进程无法访问该文件,因为它正在被另一个进程使用:'abc.txt'
  • 那很奇怪...想到的选项很少 - 1. 您的系统上没有 sleep.exe(尽管这不会是错误 32),2. 可能它受到某种影响其余的代码。您是否仅在解释器中尝试过?
【解决方案2】:

在您生成子进程的主 python 脚本中,发送/传递一个 Event 对象,并在主进程中保持对子进程的引用

示例代码:

from multiprocessing import Process, Event

# sub process execution point
def process_function(event):
    # if event is set by main process then this process exits from the loop
    while not event.is_set():
        # do something

# main process

process_event = {}  #  to keep reference of subprocess and their events
event = Event()
p = Process(target=process_function, args=(event))
p.start()
process_event[p] = event

# when you want to kill all subprocess
for process in process_event:
    event = process_event[process]
    event.set()

编辑
正如您对问题的评论,我认为它在您的场景中不是很有用,因为您使用的是 subprocess.Popen。但是一个不错的技巧

【讨论】:

    【解决方案3】:

    你可以使用os.kill函数

    import os
    os.kill(process.pid)
    

    如果您使用subprocess.Popen 函数打开子进程,则已返回进程ID。但如果您使用shell=True 标志请小心,因为在这种情况下,进程 pid 将是 shell 进程 ID。如果这是您的情况,here 是一个可行的解决方案。

    【讨论】:

    • 是的,我使用的是 Shell=True 标志。
    • 那么这可以帮助你stackoverflow.com/questions/4789837/…
    • os.killpg 在 windows 下工作了吗?
    • 我不确定您是否必须尝试一下。
    • 这不会杀死孩子
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-06
    • 2013-08-19
    相关资源
    最近更新 更多