杀死除当前进程之外的所有python主进程

杀死除当前进程之外的所有python主进程,python,process,Python,Process,考虑以下脚本: import matplotlib.pyplot as plt plt.plot([1,2,3], [1,2,3]) plt.show() 每次运行它时,如果您之前没有关闭图形,它就会在新的python.exe进程中创建一个新图形。但我想关闭所有以前打开的图形(这只是一个示例,请不要使用matplotlib解决方案),这意味着所有以前打开的进程 这是我的方法: 使用os 使用psutil 从所有python ID中筛选出当前ID 杀死剩余的ID列表 它可以工作,它关闭除当前

考虑以下脚本:

import matplotlib.pyplot as plt

plt.plot([1,2,3], [1,2,3])
plt.show()
每次运行它时,如果您之前没有关闭图形,它就会在新的python.exe进程中创建一个新图形。但我想关闭所有以前打开的图形(这只是一个示例,请不要使用matplotlib解决方案),这意味着所有以前打开的进程

这是我的方法:

  • 使用
    os
  • 使用
    psutil
  • 从所有python ID中筛选出当前ID
  • 杀死剩余的ID列表

  • 它可以工作,它关闭除当前进程之外的所有打开的python进程。 但是,当实际有进程要关闭时,我会出现以下错误:

    回溯(最近一次调用last):文件“C:..py”,第10行,在 对于PyIdsToKill中的PyId:OSError:[WinError 87]Falscher参数[在0.3s内完成,退出代码为1]

    我犯了什么错?


    我在Windows 7 Pro上运行:

    Python 3.4.3(v3.4.3:9b73f1c3e601,2015年2月24日,22:44:40)[MSC v.1600 win32上的64位(AMD64)]


    如果不以跨平台兼容性为目标,也可以使用taskkill:


    您已在
    os.kill
    中硬编码了信号
    1
    1
    应该是什么?在Unix上是
    SIGHUP
    ,但在Windows上没有这样的功能。我建议使用
    信号
    模块中定义的常数,如下所示:

    os.kill(PyId, signal.SIGTERM)
    

    你也可以考虑使用<代码> SigIt< /C> >

    < p>不确定这是否会帮助你,但是我通过获得PID来杀死除了当前进程之外的所有进程,但是当我从Atom运行代码时,2个进程开始了。所以我也必须按日期匹配PID不匹配的那个

    快乐编码

    import re, datetime, psutil, os
    print('current process: '+str(os.getpid()))
    for process in psutil.process_iter():
        if str(process.pid) == str(os.getpid()):
            current_started = re.findall(r'\d{1,2}:\d{1,2}:\d{1,2}', str(process))[0]
    
    for process in psutil.process_iter():
        if "python.exe" in str(process.name):
            if str(process.pid) != str(os.getpid()):
                if str(current_started)!= re.findall(r'\d{1,2}:\d{1,2}:\d{1,2}', str(process))[0]:
                    os.system("Taskkill /PID "+str(process.pid)+"")
    

    我从这个题目的其他答案中得到了1分,这似乎很有效。谢谢你的提示!不客气。让这成为一个教训:不要硬编码魔术数字。
    os.kill(PyId, signal.SIGTERM)
    
    import re, datetime, psutil, os
    print('current process: '+str(os.getpid()))
    for process in psutil.process_iter():
        if str(process.pid) == str(os.getpid()):
            current_started = re.findall(r'\d{1,2}:\d{1,2}:\d{1,2}', str(process))[0]
    
    for process in psutil.process_iter():
        if "python.exe" in str(process.name):
            if str(process.pid) != str(os.getpid()):
                if str(current_started)!= re.findall(r'\d{1,2}:\d{1,2}:\d{1,2}', str(process))[0]:
                    os.system("Taskkill /PID "+str(process.pid)+"")