Skip to content

Instantly share code, notes, and snippets.

@cahna
Last active September 27, 2023 22:39
Show Gist options
  • Star 14 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save cahna/43a1a3ff4d075bcd71f9d7120037a501 to your computer and use it in GitHub Desktop.
Save cahna/43a1a3ff4d075bcd71f9d7120037a501 to your computer and use it in GitHub Desktop.
Parse the output of `ps aux` into a list of dictionaries representing the parsed process information from each row of the output.
#!/usr/bin/python
# -*- coding: utf-8 -*-
import pprint
import subprocess
def get_processes():
"""
Parse the output of `ps aux` into a list of dictionaries representing the parsed
process information from each row of the output. Keys are mapped to column names,
parsed from the first line of the process' output.
:rtype: list[dict]
:returns: List of dictionaries, each representing a parsed row from the command output
"""
output = subprocess.Popen(['ps', 'aux'], stdout=subprocess.PIPE).stdout.readlines()
headers = [h for h in ' '.join(output[0].strip().split()).split() if h]
raw_data = map(lambda s: s.strip().split(None, len(headers) - 1), output[1:])
return [dict(zip(headers, r)) for r in raw_data]
pprint.pprint(get_processes())
@webtic
Copy link

webtic commented Jun 12, 2018

cool, saved me from trying to get psutil to compile on an unsupported old os..

@ygb8745
Copy link

ygb8745 commented Jul 27, 2023

In python3, output need to decode:
output = [i.decode('UTF-8') for i in output]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment