ps-mem: Per-Program Memory Usage Reporter

3.14 · active · verified Tue Apr 14

ps-mem is a Python utility designed to accurately report the core memory usage per program on Linux, distinguishing itself from tools that report per-process. It calculates RAM usage by summing both private and shared memory across all processes belonging to a given program. The current stable version is 3.14, released in May 2022, and it operates as a command-line tool, primarily written in Python 3, though it also supported Python 2.

Warnings

Install

Imports

Quickstart

The primary way to use ps-mem programmatically is to execute it as an external command using `subprocess`, mimicking its typical command-line usage. A more advanced method involves directly calling `ps_mem.main()`, but this requires careful handling of `sys.argv` and `sys.stdout`.

import subprocess
import os

# Example 1: Run ps_mem as a command to get total memory usage
# Note: ps_mem often requires root privileges for full accuracy.
# This example tries without sudo first.

try:
    # Using a common flag like -t for total or no flags for default output
    result = subprocess.run(['ps_mem', '-t'], capture_output=True, text=True, check=True)
    print("\n--- ps_mem (total) output ---")
    print(result.stdout)
except FileNotFoundError:
    print("Error: 'ps_mem' command not found. Ensure it's installed and in your PATH.")
except subprocess.CalledProcessError as e:
    print(f"Error running ps_mem: {e}")
    print(f"Stderr: {e.stderr}")
    print("Note: ps_mem often requires root privileges. Try running with sudo if you encounter permission errors.")

# Example 2: Programmatic call to ps_mem's main function (more advanced, requires mocking)
# This is illustrative and not typically recommended for simple use cases due to sys.argv/stdout manipulation.
import sys
from io import StringIO
from unittest.mock import patch

# Assuming ps_mem is installed and available in your Python environment
try:
    import ps_mem

    # Capture stdout and mock sys.argv
    captured_output = StringIO()
    with patch('sys.argv', ['ps_mem', '-S']), \
         patch('sys.stdout', captured_output):
        # Call the main function with desired arguments (e.g., -S for swap info)
        # ps_mem.main() might call sys.exit(), so wrap it if needed or catch SystemExit.
        try:
            ps_mem.main()
        except SystemExit as e:
            if e.code != 0: # 0 means successful exit
                print(f"ps_mem.main() exited with error code {e.code}")

    output_from_main = captured_output.getvalue()
    print("\n--- ps_mem.main() programmatic output ---")
    print(output_from_main)

except ImportError:
    print("Error: 'ps_mem' module not found. Install with 'pip install ps-mem'.")
except Exception as e:
    print(f"An unexpected error occurred during programmatic call: {e}")

view raw JSON →