Skip to content

Instantly share code, notes, and snippets.

@mgbckr
Created May 15, 2023 16:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mgbckr/24895ebff18c487d761db2c4d57e8096 to your computer and use it in GitHub Desktop.
Save mgbckr/24895ebff18c487d761db2c4d57e8096 to your computer and use it in GitHub Desktop.
Get %CPU and %MEM for each process on Linux (using Python)
import pandas as pd
import subprocess
# 'ps aux'
output = subprocess.check_output(['ps', 'aux']).decode('utf-8')
# split lines
lines = output.split('\n')
# headers
headers = lines[0].split()
# remove the first line (column headers) and empty lines
lines = [line for line in lines[1:] if line]
# list of dictionaries where each dictionary represents a process entry
processes = [dict(zip(headers, line.split())) for line in lines]
# create DataFrame from the list of dictionaries
df = pd.DataFrame(processes)
df["%MEM"] = df["%MEM"].astype("float")
df["%CPU"] = df["%CPU"].astype("float")
# cacculate stats by process name
df_stats = df[["COMMAND", "%MEM", "%CPU"]].groupby("COMMAND").sum()
# show stats sorted by %MEM
df_stats.sort_values("%MEM", ascending=False).head(25)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment