Monitoring disk space using Python.

python @ Freshers.in

Python script to monitor disk space on Windows, Linux, and macOS involves using cross-platform libraries and system-specific commands. Here’s a detailed guide on how to achieve this:

1. Introduction

Monitoring disk space is crucial for system administrators and users to avoid running out of storage, which can lead to various issues. This article will guide you through creating a Python script that works across Windows, Linux, and macOS.

2. Prerequisites

  • Python installed on your system (Python 3.x is recommended).
  • Basic knowledge of Python programming.
  • Familiarity with the command line on your operating system.

3. Cross-Platform Compatibility

The psutil library in Python provides an easy way to retrieve information about system utilization (such as CPU, memory, disks, network, sensors) in a cross-platform way. We will use this library to monitor disk space.

Sample code

import psutil
import sys

def check_disk_space():
    partitions = psutil.disk_partitions()
    for p in partitions:
        print(f"Checking partition: {p.device}")
        try:
            usage = psutil.disk_usage(p.mountpoint)
        except PermissionError:
            # This can happen on some systems
            continue

        print(f"  Total Size: {usage.total / (1024 * 1024 * 1024)} GB")
        print(f"  Used: {usage.used / (1024 * 1024 * 1024)} GB")
        print(f"  Free: {usage.free / (1024 * 1024 * 1024)} GB")
        print(f"  Percentage: {usage.percent}%\n")

def main():
    print("Disk Space Monitor\n")
    check_disk_space()

if __name__ == "__main__":
    main()

The script will display information about each partition, including its total size, used space, free space, and the percentage of space used.

psutil documentation

Python’s official documentation

Refer more on python here :

Author: user