Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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())
@cahna

This comment has been minimized.

Copy link
Owner Author

@cahna cahna commented Oct 13, 2016

Example output:

[{
  '%CPU': '6.2',
  '%MEM': '0.0',
  'COMMAND': '/opt/local/Library/Frameworks/Python.framework/Versions/2.7/Resources/Python.app/Contents/MacOS/Python tester.py',
  'PID': '62826',
  'RSS': '5284',
  'STARTED': '10:34AM',
  'STAT': 'S+',
  'TIME': '0:00.03',
  'TT': 's000',
  'USER': 'jdoe',
  'VSZ': '2468628'
},
{
  '%CPU': '5.9',
  '%MEM': '0.4',
  'COMMAND': '/Applications/iTerm.app/Contents/MacOS/iTerm2',
  'PID': '61467',
  'RSS': '61248',
  'STARTED': '9:23AM',
  'STAT': 'S',
  'TIME': '0:13.82',
  'TT': '??',
  'USER': 'jdoe',
  'VSZ': '2677452'
},
...
]
@eteamin

This comment has been minimized.

Copy link

@eteamin eteamin commented May 20, 2018

thanks

@webtic

This comment has been minimized.

Copy link

@webtic webtic commented Jun 12, 2018

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

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