Question

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?

Was it helpful?

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

OTHER TIPS

Shx2, thank you for your response. While your solution is better for multiplatform support, here's the solution I went with since I'm only running Windows 8.1.

 from win32com.client import GetObject

 Wmi = GetObject('winmgmts:')
 processes = Wmi.InstancesOf('Win32_Process')

 # Get the Explorer process
 explorer = Wmi.ExecQuery('select * from Win32_Process where Name="explorer.exe"')

 # Grab its Pid
 processId = explorer[0].Properties_('ProcessId').Value
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top