Search code examples
pythonpython-2.7subprocesswmipid

Get list of Windows 8.1 processes using Python


I want to get the list of processes in memory including the name and the PID in Windows 8.1.

Here's my code:

import subprocess
import os

cmd = "WMIC PROCESS get Caption,ProcessId"
proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
for line in proc.stdout:
  # Additional logic here

The loop never runs. This code worked in an earlier version of Windows 8. Is there a different approach someone can recommend?


Solution

  • Instead of the cumbersome subprocess, you can use the fabolous, cross-platform psutil library.

    Using the general purpose psutil.process_iter() will allow you to do pretty much anything you'd like with the Process objects it returns (get name, pid, filter the ones you're interested in, etc.)

    E.g.

    for proc in psutil.process_iter():
        print proc.pid, proc.name