Based on a few of the other answers...
import subprocess
import re
def get_processes_running():
""" Takes tasklist output and parses the table into a dict
Example:
C:UsersUser>tasklist
Image Name PID Session Name Session# Mem Usage
========================= ======== ================ =========== ============
System Idle Process 0 Services 0 24 K
System 4 Services 0 43,064 K
smss.exe 400 Services 0 1,548 K
csrss.exe 564 Services 0 6,144 K
wininit.exe 652 Services 0 5,044 K
csrss.exe 676 Console 1 9,392 K
services.exe 708 Services 0 17,944 K
lsass.exe 728 Services 0 16,780 K
winlogon.exe 760 Console 1 8,264 K
# ... etc...
Returns:
[ {'image': 'System Idle Process', 'mem_usage': '24 K', 'pid': '0', 'session_name': 'Services', 'session_num': '0'},
{'image': 'System', 'mem_usage': '43,064 K', 'pid': '4', 'session_name': 'Services', 'session_num': '0'},
{'image': 'smss.exe', 'mem_usage': '1,548 K', 'pid': '400', 'session_name': 'Services', 'session_num': '0'},
{'image': 'csrss.exe', 'mem_usage': '6,144 K', 'pid': '564', 'session_name': 'Services', 'session_num': '0'},
{'image': 'wininit.exe', 'mem_usage': '5,044 K', 'pid': '652', 'session_name': 'Services', 'session_num': '0'},
{'image': 'csrss.exe', 'mem_usage': '9,392 K', 'pid': '676', 'session_name': 'Console', 'session_num': '1'},
{'image': 'services.exe', 'mem_usage': '17,892 K', 'pid': '708', 'session_name': 'Services', 'session_num': '0'},
{'image': 'lsass.exe', 'mem_usage': '16,764 K', 'pid': '728', 'session_name': 'Services', 'session_num': '0'},
{'image': 'winlogon.exe', 'mem_usage': '8,264 K', 'pid': '760', 'session_name': 'Console', 'session_num': '1'},
#... etc...
]
"""
tasks = subprocess.check_output(['tasklist']).split("
")
p = []
for task in tasks:
m = re.match("(.+?) +(d+) (.+?) +(d+) +(d+.* K).*",task)
if m is not None:
p.append({"image":m.group(1),
"pid":m.group(2),
"session_name":m.group(3),
"session_num":m.group(4),
"mem_usage":m.group(5)
})
return p