Code: Alles auswählen
#!/usr/bin/env python
# -*- coding: iso-8859-1 -*-
"""
Returns processinfos. (pid, name and size_kb)
Free for everybody. (by gerold)
"""
import sys
import os
def get_current_processes():
"""
Returns processinfos. (pid, name and size_kb)
On Windows-Systems, it uses ``tasklist.exe`` or WMI to list the processes.
On other platforms, it reads the "/proc"-directory.
:return: Dictionary with PID's as keys and the infos as values in an
inner dictionary. (It is possible, that "size_kb" doesn't exist.):
{
123: {"name": "bash", "pid": 123},
234: {"name": "mc", "pid": 234, "size_kb": 1000},
}
"""
retdict = {}
if sys.platform.startswith("win"):
# tasklist.exe runs on Windows XP and higher. (To parse the ouput of
# tasklist.exe is faster than WMI.)
import csv
csvlines = []
for line in os.popen("tasklist.exe /fo csv /nh"):
line = line.strip()
if line:
csvlines.append(line)
for line in csv.reader(csvlines):
pid = int(line[1])
details = {
"name": line[0].decode("cp850"), # to unicode
"pid": pid,
}
value = "".join(
char for char in line[4]
if char in "0123456789"
)
details["size_kb"] = int(value)
retdict[pid] = details
if not csvlines:
try:
from win32com.client import GetObject
# pywin32 is installed --> use WMI
wmi = GetObject('winmgmts:')
processes = wmi.InstancesOf('Win32_Process')
for process in processes:
pid = int(process.Properties_("ProcessId").value)
details = {
"name": process.Properties_("Name").value,
"pid": pid,
"size_kb": int(process.Properties_("WorkingSetSize").value) / 1000
}
retdict[pid] = details
except ImportError:
raise NotImplementedError("No tasklist.exe and no WMI.")
else:
# Linux, Cygwin
from glob import glob
for filename in glob("/proc/*/status"):
try:
int(filename[len("/proc/"):-len("/status")])
except ValueError:
continue
details = {}
try:
f = file(filename, "r")
try:
for line in f:
line_lower = line.lower()
if line_lower.startswith("name:"):
details["name"] = line[len("Name:"):].strip()
elif line_lower.startswith("pid:"):
details["pid"] = line[len("pid:"):].strip()
elif line_lower.startswith("vmsize:"):
value = "".join(
char for char in line[len("vmsize:"):]
if char in "0123456789"
)
details["size_kb"] = int(value)
if (
details.has_key("name") and
details.has_key("pid") and
details.has_key("size_kb")
):
break
finally:
f.close()
except IOError:
pass
if details:
retdict[details["pid"]] = details
# Return value
return retdict or None
def main():
"""Testing"""
from pprint import pformat
# Process-Infos
print pformat(get_current_processes())
if __name__ == "__main__":
main()
Trac: http://gelb.bcom.at/trac/misc/browser/processinfo
lg
Gerold