Daiver
Daiver

Reputation: 1508

Watch all system processes in Python

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

Answers (1)

Jared
Jared

Reputation: 26397

Get psutil. Something like this would give you a similar result,

{process.pid: process.exe for process in psutil.process_iter() if process.pid}

Upvotes: 2

Related Questions