More unit tests
[codimension.git] / thirdparty / pyqtermwidget / pyqterm / procinfo.py
blob5b3c9cf5caf6d4edee57720946e974960d6c79b3
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3 import os
4 import re
7 class ProcessInfo(object):
9 def __init__(self):
10 self.update()
12 def update(self):
13 processes = [int(entry)
14 for entry in os.listdir("/proc") if entry.isdigit()]
15 parent = {}
16 children = {}
17 commands = {}
18 for pid in processes:
19 try:
20 f = open("/proc/%s/stat" % pid)
21 except IOError:
22 continue
23 stat = f.read().split()
24 f.close()
25 cmd = stat[1]
26 ppid = int(stat[3])
27 parent[pid] = ppid
28 children.setdefault(ppid, []).append(pid)
29 commands[pid] = cmd
30 self.parent = parent
31 self.children = children
32 self.commands = commands
34 def all_children(self, pid):
35 cl = self.children.get(pid, [])[:]
36 for child_pid in cl:
37 cl.extend(self.children.get(child_pid, []))
38 return cl
40 def dump(self, pid, _depth=0):
41 print " " * (_depth * 2), pid, self.commands[pid]
42 for child_pid in self.children.get(pid, []):
43 self.dump(child_pid, _depth + 1)
45 def cwd(self, pid):
46 try:
47 path = os.readlink("/proc/%s/cwd" % pid)
48 except OSError:
49 return
50 return path
53 if __name__ == "__main__":
54 pi = ProcessInfo()
55 pi.dump(4984)
56 print pi.all_children(4984)
57 print pi.cwd(4984)
58 print pi.cwd(pi.all_children(4984)[-1])