import os from string import split from stat import * class FSNode: def __init__(self, path): if path[-1] == '/': path = path[0:-1] self.path = path def list(self): return os.listdir(self.path) def lstat(self): # TODO cache? return os.lstat(self.path) def readlink(self): return os.readlink(self.path) def open(self, mode='r'): # TODO buffer? return open(self.path, mode) def read(self): file = open(self.path) return file.read() # TODO do we need to close the file explicitly? def get(self, path): path = self.abspath(path) return FSNode(path) def abspath(self, path): if path[0] == '/': return self.path + path return self.path + '/' + path class System(FSNode): def __init__(self): FSNode.__init__(self, "/proc") def process(self, pid): return Process(pid, self) def pids(self): entries = self.list() pids = [] for entry in entries: try: pids.append(int(entry)) except ValueError: pass return pids system = System() class Process(FSNode): def __init__(self, pid, system=system): FSNode.__init__(self, system.path + "/" + str(pid)) self.system = system self.pid = pid try: self.cwd = self.get("cwd").readlink() except OSError: self.cwd = None try: self.root = self.get("root").readlink() except OSError: self.root = None try: self.cmdline = self.get("cmdline").read() if self.cmdline: self.cmdline = split(self.cmdline, '\0') except OSError: self.cmdline = None try: self.exe = self.get("exe").readlink() except OSError: self.exe = None self.stat = self.get("stat").read() self.statm = self.get("statm").read() self.status = self.get("status").read() self.updateEnviron() def updateEnviron(self): self.environ = {} environ = self.get("environ") if environ: environ = environ.read() if environ != '': for keyval in split(environ, '\0'): list = split(keyval, '=', 1) if len(list) == 2: self.environ[list[0]] = list[1] else: self.environ[list[0]] = None def fds(self): try: return map(int, self.get("fd").list()) except OSError: return [] def fd(self, fd): return FD(self, fd) class FD(FSNode): def __init__(self, process, fd): FSNode.__init__(self, process.path + "/fd/" + str(fd)) self.process = process self.fd = fd self.file = self.readlink() self.stat = self.lstat() for pid in system.pids(): process = Process(pid) fds = process.fds() print process.exe, if len(process.cmdline) > 1: for word in process.cmdline[1:]: print word, if 0 in fds: print "<", process.fd(0).file, if 1 in fds: print ">", process.fd(1).file, if 2 in fds: print "2>", process.fd(2).file, print # print pid, process.exe, process.cwd, process.cmdline # print process.environ