Created
September 3, 2024 20:52
-
-
Save jrelo/5d692b5598032b4d16b19ebbeffdd84e to your computer and use it in GitHub Desktop.
swap usage per process
This file contains 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
#!/usr/bin/env python3 | |
import os | |
import re | |
import psutil | |
import tempfile | |
def get_swap_usage(): | |
swap_data = [] | |
total_swap = 0 | |
# Iterate through all process directories in /proc/ | |
for pid in [d for d in os.listdir('/proc') if d.isdigit()]: | |
try: | |
# Get the program name | |
proc_name = psutil.Process(int(pid)).name() | |
# Calculate the total swap used by this process | |
swap_usage = 0 | |
smaps_file = f'/proc/{pid}/smaps' | |
if os.path.exists(smaps_file): | |
with open(smaps_file, 'r') as f: | |
for line in f: | |
if 'Swap:' in line: | |
swap_usage += int(line.split()[1]) | |
if swap_usage > 0: | |
swap_data.append((int(pid), swap_usage, proc_name)) | |
total_swap += swap_usage | |
except (psutil.NoSuchProcess, FileNotFoundError): | |
# Process might have ended or the smaps file might not exist | |
continue | |
return swap_data, total_swap | |
def print_swap_usage(swap_data, total_swap, sort_by): | |
if sort_by == "name": | |
swap_data.sort(key=lambda x: x[2].lower(), reverse=True) | |
print(f"{'Name':<25} {'kB':>10} {'PID':>10}") | |
elif sort_by == "kb": | |
swap_data.sort(key=lambda x: x[1], reverse=True) | |
print(f"{'kB':>10} {'PID':>10} {'Name':<25}") | |
else: | |
swap_data.sort(key=lambda x: x[0], reverse=True) | |
print(f"{'PID':>10} {'kB':>10} {'Name':<25}") | |
print("=" * 50) | |
for pid, swap_usage, proc_name in swap_data: | |
if sort_by == "name": | |
print(f"{proc_name:<25} {swap_usage:>10} {pid:>10}") | |
elif sort_by == "kb": | |
print(f"{swap_usage:>10} {pid:>10} {proc_name:<25}") | |
else: | |
print(f"{pid:>10} {swap_usage:>10} {proc_name:<25}") | |
print("=" * 50) | |
print(f"Overall swap used: {total_swap} kB") | |
print("=" * 50) | |
def main(): | |
sort_by = "kb" # Default sort by kb | |
if len(os.sys.argv) > 1: | |
sort_by = os.sys.argv[1].lower() | |
swap_data, total_swap = get_swap_usage() | |
print_swap_usage(swap_data, total_swap, sort_by) | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment