178
|
1 import os
|
|
2 import shlex
|
|
3 import subprocess
|
|
4 import sys
|
|
5
|
179
|
6 def ps(arg='axwww'):
|
180
|
7 """
|
|
8 python front-end to `ps`
|
|
9 http://en.wikipedia.org/wiki/Ps_%28Unix%29
|
|
10 returns a list of process dicts based on the `ps` header
|
|
11 """
|
178
|
12 retval = []
|
179
|
13 process = subprocess.Popen(['ps', arg], stdout=subprocess.PIPE)
|
178
|
14 stdout, _ = process.communicate()
|
|
15 header = None
|
|
16 for line in stdout.splitlines():
|
|
17 line = line.strip()
|
|
18 if header is None:
|
|
19 # first line is the header
|
|
20 header = line.split()
|
|
21 continue
|
|
22 split = line.split(None, len(header)-1)
|
|
23 process_dict = dict(zip(header, split))
|
|
24 retval.append(process_dict)
|
|
25 return retval
|
|
26
|
180
|
27 def running_processes(name, defunct=True):
|
178
|
28 """
|
|
29 returns a list of
|
|
30 {'PID': PID of process (int)
|
|
31 'command': command line of process (list)}
|
180
|
32 with the executable named `name`.
|
|
33 - defunct: whether to return defunct processes
|
178
|
34 """
|
|
35 retval = []
|
|
36 for process in ps():
|
|
37 command = process['COMMAND']
|
|
38 command = shlex.split(command)
|
180
|
39 if command[-1] == '<defunct>':
|
|
40 command = command[:-1]
|
|
41 if not command or not defunct:
|
|
42 continue
|
178
|
43 prog = command[0]
|
|
44 basename = os.path.basename(prog)
|
|
45 if basename == name:
|
|
46 retval.append((int(process['PID']), command))
|
|
47 return retval
|
|
48
|
|
49 if __name__ == '__main__':
|
|
50 for arg in sys.argv[1:]:
|
|
51 processes = running_processes(arg)
|
|
52 for pid, command in processes:
|
|
53 print '%s %s : %s' % (pid, arg, command)
|