2

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?

2
  • Does the actual command line still work? Commented Apr 14, 2014 at 21:18
  • Yes it does. I can run "WMIC PROCESS get Caption,ProcessId" in the command line (cmd), and it gives me exactly what I want. Commented Apr 15, 2014 at 2:07

2 Answers 2

3

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
Sign up to request clarification or add additional context in comments.

1 Comment

This is a great solution, so I am marking it as the answer.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.