comparison python/process.py @ 180:f52486ceadee

handle defunct processes
author Jeff Hammel <jhammel@mozilla.com>
date Tue, 08 Nov 2011 17:11:35 -0800
parents a5061b41a781
children f9863f733344
comparison
equal deleted inserted replaced
179:a5061b41a781 180:f52486ceadee
2 import shlex 2 import shlex
3 import subprocess 3 import subprocess
4 import sys 4 import sys
5 5
6 def ps(arg='axwww'): 6 def ps(arg='axwww'):
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 """
7 retval = [] 12 retval = []
8 process = subprocess.Popen(['ps', arg], stdout=subprocess.PIPE) 13 process = subprocess.Popen(['ps', arg], stdout=subprocess.PIPE)
9 stdout, _ = process.communicate() 14 stdout, _ = process.communicate()
10 header = None 15 header = None
11 for line in stdout.splitlines(): 16 for line in stdout.splitlines():
17 split = line.split(None, len(header)-1) 22 split = line.split(None, len(header)-1)
18 process_dict = dict(zip(header, split)) 23 process_dict = dict(zip(header, split))
19 retval.append(process_dict) 24 retval.append(process_dict)
20 return retval 25 return retval
21 26
22 def running_processes(name): 27 def running_processes(name, defunct=True):
23 """ 28 """
24 returns a list of 29 returns a list of
25 {'PID': PID of process (int) 30 {'PID': PID of process (int)
26 'command': command line of process (list)} 31 'command': command line of process (list)}
27 with the executable named `name` 32 with the executable named `name`.
33 - defunct: whether to return defunct processes
28 """ 34 """
29 retval = [] 35 retval = []
30 for process in ps(): 36 for process in ps():
31 command = process['COMMAND'] 37 command = process['COMMAND']
32 command = shlex.split(command) 38 command = shlex.split(command)
39 if command[-1] == '<defunct>':
40 command = command[:-1]
41 if not command or not defunct:
42 continue
33 prog = command[0] 43 prog = command[0]
34 basename = os.path.basename(prog) 44 basename = os.path.basename(prog)
35 if basename == name: 45 if basename == name:
36 retval.append((int(process['PID']), command)) 46 retval.append((int(process['PID']), command))
37 return retval 47 return retval