使用 Python 进行 Windows 进程管理

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2084111/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 13:46:46  来源:igfitidea点击:

Windows process management using Python

pythonwindowsprocess

提问by Vicky

I need a script that check if a particular process is running and return something if not found. I know that this can be done using subprocess, but is there a simpler way to do it?

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

回答by luc

On Windows, you can use WMI:

在 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")

回答by Micha? Niklas

回答by Robert Lujo

For similar purposes I have used psutillibrary. Some hints:

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

  • list processes with psutil.pids()(reference)
  • inspect process information with process = psutil.Process(pid)(reference)
  • do process.killor process.terminate()
  • 使用psutil.pids()参考)列出进程
  • 使用process = psutil.Process(pid)参考)检查过程信息
  • process.killprocess.terminate()

Installationon windows - pipwill do installation from the source (which means compiling), so you probably want to download binary installation from https://pypi.python.org/pypi/psutil/#downloads.

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