- Courses
- 💻Programming Languages
- 🐍Python
- Standard Library Deep Dive
- Guided Exercise: Build a System Utility Suite
On this page
Guided Exercise: Build a System Utility Suite
By Enrico Hochkoeppler
Web Developer & TutoriaLibre Founder
Overview
This guided exercise consolidates everything learned in the OS & Filesystem, Datetime, Random & Secrets, and Subprocess lessons.
You will build a modular system utility suite: a collection of small, professional‑grade command‑line utilities that automate common system tasks.
You will practice:
- Running external commands with
subprocess - Inspecting and manipulating the filesystem with
pathlib - Using
osandshutilsafely - Generating secure tokens with
secrets - Logging timestamps with
datetime - Structuring a clean, modular Python project
This mirrors real‑world automation and DevOps scripting.
Project Structure
A clean, modular layout:
system_utils/
__init__.py
disk.py
processes.py
security.py
files.py
main.py
Each module focuses on one responsibility, following professional design principles.
Module 1 — Disk & Filesystem Utilities (disk.py)
Purpose
Provide utilities for inspecting disk usage, listing directories, and checking file metadata.
Example Implementation
from pathlib import Path
import shutil
def list_directory(path: str) -> list[str]:
p = Path(path)
return [str(item) for item in p.iterdir()]
def disk_usage(path: str) -> dict:
usage = shutil.disk_usage(path)
return {
"total": usage.total,
"used": usage.used,
"free": usage.free
}
def file_info(path: str) -> dict:
p = Path(path)
stat = p.stat()
return {
"size": stat.st_size,
"modified": stat.st_mtime,
"created": stat.st_ctime
}
Module 2 — Process Utilities (processes.py)
Purpose
Run external commands safely and capture output.
Example Implementation
import subprocess
def run_command(cmd: list[str]) -> dict:
result = subprocess.run(
cmd,
capture_output=True,
text=True
)
return {
"stdout": result.stdout,
"stderr": result.stderr,
"returncode": result.returncode
}
def is_program_available(name: str) -> bool:
result = subprocess.run(
["which", name],
capture_output=True,
text=True
)
return result.returncode == 0
This module abstracts away subprocess complexity.
Module 3 — Security Utilities (security.py)
Purpose
Generate secure tokens and identifiers.
Example Implementation
import secrets
def generate_hex_token(n_bytes: int = 16) -> str:
return secrets.token_hex(n_bytes)
def generate_url_token(n_bytes: int = 32) -> str:
return secrets.token_urlsafe(n_bytes)
These utilities are essential for authentication systems and secure automation.
Module 4 — File Operations (files.py)
Purpose
Provide safe, high‑level file operations.
Example Implementation
from pathlib import Path
import shutil
def copy_file(src: str, dst: str) -> None:
shutil.copy(src, dst)
def move_file(src: str, dst: str) -> None:
shutil.move(src, dst)
def delete_file(path: str) -> None:
p = Path(path)
if p.exists():
p.unlink()
These functions wrap common filesystem tasks with clean, reusable logic.
Module 5 — Main Command Interface (main.py)
Purpose
Provide a simple command‑line interface that ties all utilities together.
Example Implementation
from datetime import datetime
from disk import list_directory, disk_usage
from processes import run_command
from security import generate_hex_token
from files import copy_file
def main():
print("System Utility Suite")
print("Timestamp:", datetime.now().isoformat())
print("\nDisk Usage:")
print(disk_usage("."))
print("\nDirectory Listing:")
print(list_directory("."))
print("\nRunning 'ls -l':")
print(run_command(["ls", "-l"])["stdout"])
print("\nSecure Token:")
print(generate_hex_token(16))
if __name__ == "__main__":
main()
This creates a cohesive, professional system utility suite.
Optional Enhancements
- Add logging with timestamps
- Add argument parsing with
argparse - Add colored terminal output
- Add a configuration file for defaults
- Add a module for compression (
zipfile,tarfile) - Add a monitoring module that watches directories for changes
Each enhancement builds real‑world automation skills.
Summary
In this guided exercise, you built a modular system utility suite using:
- Subprocess for running external commands
- Pathlib, os, and shutil for filesystem operations
- Secrets for secure token generation
- Datetime for timestamping
- Clean, professional module organization
This project mirrors real automation, DevOps, and system‑level scripting used in production environments.
Found this helpful? Share the knowledge...
... or support this project to keep it alive!
Previous
Subprocess & System Interaction
Next
Automation & Scripting
-
Overview
-
Project Structure
-
Module 1 — Disk & Filesystem Utilities (
disk.py)- Purpose
- Example Implementation
-
Module 2 — Process Utilities (
processes.py)- Purpose
- Example Implementation
-
Module 3 — Security Utilities (
security.py)- Purpose
- Example Implementation
-
Module 4 — File Operations (
files.py)- Purpose
- Example Implementation
-
Module 5 — Main Command Interface (
main.py)- Purpose
- Example Implementation
-
Optional Enhancements
-
Summary
