Hello, Please write me a script, to check for the swap memory every 10 minutes and request in a pop-up a restart when the swap is higher than 1.90 GB out of the 2 GB available
Assistant
Of course. Here is a Python script that monitors your swap memory usage. It checks every 10 minutes and sends a critical desktop notification requesting a restart if the usage exceeds 1.90 GiB.This kind of script can be particularly useful in your AI research, where memory-intensive tasks like training models or processing large datasets might cause the system to swap heavily, impacting performance. Staying ahead of this helps keep your workflow smooth.The Python ScriptSave the following code into a file named swap_monitor.py in your home directory or another convenient location.Python#!/usr/bin/env python3
import psutil
import time
import subprocess
import sys
--- Configuration ---
Threshold for used swap memory in GiB. The script will trigger if usage is HIGHER than this.
SWAP_THRESHOLD_GB = 1.90
Interval between checks in seconds. 600 seconds = 10 minutes.
CHECK_INTERVAL_SECONDS = 600
def send_notification(used_gb: float):
"""Sends a desktop notification using the notify-send command."""
title = "High Swap Memory Alert!"
message = (
f"Current swap usage is {used_gb:.2f} GiB of 2.00 GiB.\n"
"A system restart is recommended to ensure optimal performance."
)
try:
# Use notify-send, a standard tool for sending notifications on Ubuntu.
# The '-u critical' flag makes the notification urgent and persistent.
subprocess.run(
['notify-send', '-u', 'critical', title, message],
check=True
)
print(f"INFO: Notification sent. Swap usage is {used_gb:.2f} GiB.")
except FileNotFoundError:
print("ERROR: 'notify-send' command not found. Please install it with 'sudo apt install libnotify-bin'")
sys.exit(1) # Exit if notification tool is missing
except subprocess.CalledProcessError as e:
print(f"ERROR: Failed to send notification. Error: {e}")
def monitor_swap():
"""Monitors swap usage and sends a notification if it exceeds the threshold."""
print("--- Swap Memory Monitor Started ---")
print(f"Checking every {CHECK_INTERVAL_SECONDS / 60:.0f} minutes.")
print(f"Alerting when swap usage is > {SWAP_THRESHOLD_GB} GiB.")
code
# Convert the threshold from GiB to bytes for accurate comparison.
threshold_bytes = SWAP_THRESHOLD_GB * (1024**3)
while True:
try:
swap = psutil.swap_memory()
used_gb = swap.used / (1024**3)
# Uncomment the line below for debugging each check
# print(f"DEBUG: Current Swap Usage: {used_gb:.2f} GiB")
if swap.used > threshold_bytes:
send_notification(used_gb)
time.sleep(CHECK_INTERVAL_SECONDS)
except KeyboardInterrupt:
print("\n--- Swap Memory Monitor Stopped By User ---")
break
except Exception as e:
print(f"An unexpected error occurred: {e}")
# Wait for a minute before retrying to prevent error loops
time.sleep(60)
if name == "main":
monitor_swap()
How to Set It UpFollow these steps to get the monitor running on your Ubuntu system.Step 1: Install PrerequisitesThe script depends on two things: the psutil library for Python to get system information, and libnotify-bin for the pop-up notification command.Open a terminal and run the following commands:Bash# Update your package list
sudo apt update
Install pip (Python's package installer) and the notification tool
sudo apt install python3-pip libnotify-bin -y
Install the psutil library
pip3 install psutil
Step 2: Run the Script for TestingBefore setting it to run automatically, you can test it directly from your terminal. Navigate to where you saved the file and run:Bashpython3 swap_monitor.py
You will see a message that the monitor has started. You can stop it by pressing Ctrl+C.Automate on StartupTo make this a "set and forget" utility, you should configure it to start automatically every time you log in. The easiest way is using Ubuntu's Startup Applications tool.Open Startup Applications: Press the Super key (Windows key), type "Startup Applications", and open it.Add a New Program: Click the "Add" button.Fill in the Details:Name: Swap Memory MonitorCommand: python3 /home/your_username/swap_monitor.py (❗Important: Replace your_username with your actual username and use the full, absolute path to the script).Comment: Alerts when swap usage is high.Save: Click "Add".The script will now start automatically the next time you log in and run silently in the background, only alerting you when necessary.