【问题标题】:Windows process management using Python使用 Python 进行 Windows 进程管理
【发布时间】:2010-01-18 05:46:32
【问题描述】:

我需要一个脚本来检查特定进程是否正在运行,如果未找到则返回某些内容。我知道这可以使用子进程来完成,但是有没有更简单的方法呢?

【问题讨论】:

    标签: python windows process


    【解决方案1】:

    在 Windows 上,您可以使用 WMI:

    import win32com.client
    
    def find_process(name):
        objWMIService = win32com.client.Dispatch("WbemScripting.SWbemLocator")
        objSWbemServices = objWMIService.ConnectServer(".", "root\cimv2")
        colItems = objSWbemServices.ExecQuery(
             "Select * from Win32_Process where Caption = '{0}'".format(name))
        return len(colItems)
    
    print find_process("SciTE.exe")
    

    【讨论】:

    • wmi 模块将使这更加容易。 timgolden.me.uk/python/wmi/index.html是win32com的轻量级封装
    • Select 语句可以让您在Caption 上进行预过滤时,为什么还要检索整个进程列表?像这样:"Select * from Win32_Process where Caption = 'SciTE.exe'"
    • 你检查过这个可以在 xp 上工作吗?我现在没有 xp 机器要检查。
    【解决方案2】:

    【讨论】:

      【解决方案3】:

      出于类似目的,我使用了psutil 库。一些提示:

      • 使用psutil.pids() (reference) 列出进程
      • 使用process = psutil.Process(pid) (reference) 检查进程信息
      • process.killprocess.terminate()

      Windows 上的Installation - pip 将从源代码进行安装(这意味着编译),因此您可能希望从 https://pypi.python.org/pypi/psutil/#downloads 下载二进制安装。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-10-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-10-04
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多