`os` and `sys` — System Interface
Python · Standard Library · Run with python3
Explanation
`os` provides a portable interface to operating system services: file/directory operations (`os.path`, `os.listdir`, `os.makedirs`, `os.remove`), environment variables (`os.environ`), process info (`os.getpid`, `os.getcwd`). `sys` exposes the Python interpreter's state: `sys.argv` (command-line args), `sys.path` (import search path), `sys.stdin`/`stdout`/`stderr`, `sys.exit()`, and `sys.version`.
Real-World Scenario
A deployment script reads `DATABASE_URL` from `os.environ`, calls `os.makedirs("logs", exist_ok=True)` to ensure the log directory exists, then launches a subprocess. `sys.exit(1)` signals failure to the calling shell or CI pipeline. ```python import os import sys # Environment variables with defaults db_url = os.environ.get("DATABASE_URL", "sqlite:///dev.db") debug = os.environ.get("DEBUG", "false").lower() == "true" # Directory operations os.makedirs("output/reports", exist_ok=True) print(os.path.abspath("output/reports")) # Process info print(f"PID: {os.getpid()}, CWD: {os.getcwd()}") print(f"Python: {sys.version_info.major}.{sys.version_info.minor}") print(f"Args: {sys.argv}") ```
Quick Snippet
import os
import sys
# Environment variables with defaults
db_url = os.environ.get("DATABASE_URL", "sqlite:///dev.db")
debug = os.environ.get("DEBUG", "false").lower() == "true"
# Directory operations
os.makedirs("output/reports", exist_ok=True)
print(os.path.abspath("output/reports"))
# Process info
print(f"PID: {os.getpid()}, CWD: {os.getcwd()}")
print(f"Python: {sys.version_info.major}.{sys.version_info.minor}")
print(f"Args: {sys.argv}")Full Example
# Compile: python3 os_sys_basics.py
# Output:
# Python version printed
import os
import sys
db_url = os.environ.get("DATABASE_URL", "sqlite:///dev.db")
debug = os.environ.get("DEBUG", "false").lower() == "true"
print(f"DB URL: {db_url}")
print(f"Debug: {debug}")
print(f"PID: {os.getpid()}")
print(f"Python: {sys.version_info.major}.{sys.version_info.minor}")
print(f"Platform: {sys.platform}")
# Directory operations
import tempfile, shutil
tmp = tempfile.mkdtemp()
nested = os.path.join(tmp, "output", "reports")
os.makedirs(nested, exist_ok=True)
print(f"Created: {os.path.exists(nested)}")
shutil.rmtree(tmp)
# os.path utilities
path = "/home/user/projects/app/main.py"
print(os.path.dirname(path)) # /home/user/projects/app
print(os.path.basename(path)) # main.py
print(os.path.splitext(path)) # ('/home/user/projects/app/main', '.py')
python3 os_sys_basics.py