Reputation: 1508
I am trying to collect some statistics (lifetime, start time/finish time, etc) about processes in my OS (Ubuntu) using Python,
One of the tasks: I wrote a function, which gets names and ids of processes in my system but it's ugly.
def get_processes():
p = subprocess.Popen(['ps', '-e'], stdout=subprocess.PIPE)
raw_string, e = p.communicate()
strings_arr = raw_string.split('\n')
strings_arr = strings_arr[1:]
processes_dict = {}
# Example of ps -e ansewer: 7 ? 00:00:00 watchdog/0
for string in strings_arr:
splted = string.split()
key, value = None, None
if len(splted) == 0: continue
for item in splted:#looking for process id
if item.isdigit():
key = int(item)
break
value = splted[-1] # looking for process name
processes_dict[key] = value
return processes_dict
Can anyone make it beautiful or propose a better solution? PS Sorry for my writing mistakes. English in not my native language.
Upvotes: 2
Views: 263