Working with OS
The Hacker’s Control Panel
Imagine you’re a hacker managing multiple servers. You need to interact directly with the operating system like listing files, checking processes, running shell commands. Python gives you two powerful control panels:
osmodule → interacts with the file system and environment.subprocessmodule → executes system commands and external programs.
Together, they let you automate system tasks, integrate with shell utilities, and build DevOps workflows.
Why OS & Subprocess
- OS Module: Provides functions for file operations, environment variables, and process management.
- Subprocess Module: Executes external commands and captures their output.
- DevOps Use Cases: File cleanup, log rotation, service restarts, monitoring, deployment scripts.
- Real‑World Analogy: Python becomes your universal controller for system operations like a hacker’s remote terminal.
OS Module Basics
import os
# Current working directory
print("CWD:", os.getcwd())
# List files
print("Files:", os.listdir("."))
# Environment variables
print("PATH:", os.environ.get("PATH"))
- Why? OS module lets you query and manipulate the system environment.
File Operations with OS
import os
# Create directory
os.makedirs("logs", exist_ok=True)
# Rename file
os.rename("old.txt", "new.txt")
# Remove file
os.remove("new.txt")
- Why? Automates file and directory management.
Subprocess Basics
import subprocess
# Run a simple command
result = subprocess.run(["echo", "Hello DevOps"], capture_output=True, text=True)
print("Output:", result.stdout)
- Why? Subprocess executes shell commands directly from Python.
Advanced Subprocess
Capturing Output
import subprocess
# Run command and capture output
result = subprocess.run(["ls", "-l"], capture_output=True, text=True)
print("Exit Code:", result.returncode)
print("Output:\n", result.stdout)
- Why? Capturing output lets you process results programmatically.
Real‑World Example
Service Monitoring
import subprocess
def check_service(service):
result = subprocess.run(["systemctl", "status", service], capture_output=True, text=True)
if "active (running)" in result.stdout:
print(f"{service} is running")
else:
print(f"{service} is NOT running")
check_service("nginx")
- Why? Automates service monitoring, crucial for DevOps workflows.
The Hacker’s Notebook
osmodule interacts with the file system and environment.subprocessexecutes external commands and captures output.- Together, they automate system tasks and integrate Python with shell utilities. Useful for monitoring, deployments, backups, and DevOps scripts.
Hacker’s Mindset: treat OS & Subprocess as your control panel. They give Python direct power over the operating system.

Updated on Jan 3, 2026