Source code for pyqterm.procinfo

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import re


[docs]class ProcessInfo(object): def __init__(self): self.update()
[docs] def update(self): processes = [int(entry) for entry in os.listdir("/proc") if entry.isdigit()] parent = {} children = {} commands = {} for pid in processes: try: f = open("/proc/%s/stat" % pid) except IOError: continue stat = parse_stat(f.read()) f.close() cmd = stat[1] try: ppid = int(stat[3]) except ValueError: print("%d %s" % (pid, stat_txt)) continue parent[pid] = ppid children.setdefault(ppid, []).append(pid) commands[pid] = cmd self.parent = parent self.children = children self.commands = commands
[docs] def all_children(self, pid): cl = self.children.get(pid, [])[:] for child_pid in cl: cl.extend(self.children.get(child_pid, [])) return cl
[docs] def dump(self, pid, _depth=0): print(" " * (_depth * 2), pid, self.commands[pid]) for child_pid in self.children.get(pid, []): self.dump(child_pid, _depth + 1)
[docs] def cwd(self, pid): try: path = os.readlink("/proc/%s/cwd" % pid) except OSError: return return path
[docs]def parse_stat(s): # # http://man7.org/linux/man-pages/man5/proc.5.html # # /proc/[pid]/stat's second field is the name of the # executable in parentheses and can contain spaces. # field1, rest = s.split(" ", 1) idx = rest.find(")") field2 = rest[1:idx] fields = [field1, field2] + rest[idx+2:].split() return fields
if __name__ == "__main__": pi = ProcessInfo() pi.dump(4984) print(pi.all_children(4984)) print(pi.cwd(4984)) print(pi.cwd(pi.all_children(4984)[-1]))