Vicky
Vicky

Reputation: 1687

Windows process management using Python

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?

Upvotes: 4

Views: 8939

Answers (2)

Robert Lujo
Robert Lujo

Reputation: 16371

For similar purposes I have used psutil library. Some hints:

  • list processes with psutil.pids() (reference)
  • inspect process information with process = psutil.Process(pid) (reference)
  • do process.kill or process.terminate()

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

Upvotes: 1

luc
luc

Reputation: 43096

On Windows, you can use 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")

Upvotes: 7

Related Questions