Created
May 15, 2023 16:08
-
-
Save mgbckr/24895ebff18c487d761db2c4d57e8096 to your computer and use it in GitHub Desktop.
Get %CPU and %MEM for each process on Linux (using Python)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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