Skip to content

Instantly share code, notes, and snippets.

@manics
Created March 20, 2014 17:25
Show Gist options
  • Save manics/9669185 to your computer and use it in GitHub Desktop.
Save manics/9669185 to your computer and use it in GitHub Desktop.
Prints out a tree of processes, repeats after one second.
#!/usr/bin/env python
# Prints out a tree of processes with cpu and memory use
# Usage: process-tree-monitor pid [-v]
import psutil
from datetime import datetime
import sys
import time
class ProcessList:
"""
Similar to psutil.process_iter
"""
def __init__(self):
self.pmap = {}
def get(self, pid):
p = self.pmap.get(pid)
if p is None or not p.is_running:
p = psutil.Process(pid)
self.pmap[pid] = p
#print '[%s]:%s' % (self.pmap[pid], p)
return p
plist = ProcessList()
def utcNow():
return datetime.isoformat(datetime.now())
def proc2str(p, verbose=False):
s = '%d %s rss:%d vms:%d cpu:%g' % (
p.pid, p.name(), p.memory_info().rss, p.memory_info().vms,
p.cpu_percent())
if verbose:
s += ' %s %s %s %s' % (
utcNow(), p.status(), p.exe(), p.cmdline())
return s
def walk_tree(parent, verbose=False, level=0):
if not isinstance(parent, psutil.Process):
parent = plist.get(parent)
if level == 0:
print utcNow()
level += 1
print (' ' * level) + proc2str(parent, verbose)
for child in parent.children():
try:
walk_tree(child.pid, verbose, level + 1)
except psutil.AccessDenied as e:
print '%s%d <AccessDenied: %s>' % (' ' * (level + 1), child.pid, e)
def main(args):
pid = int(args[1])
verbose = len(args) > 2 and args[2] == '-v'
try:
while True:
walk_tree(pid, verbose);
print;
time.sleep(1)
except KeyboardInterrupt:
print 'Exiting'
if __name__ == '__main__':
main(sys.argv)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment