python

examples

examples.py🐍
"""
12 - Real Development Modules: Examples
Run this file to see os, sys, logging, argparse in action!
"""

print("=" * 60)
print("REAL DEVELOPMENT MODULES - EXAMPLES")
print("=" * 60)

import os
import sys
from pathlib import Path
import logging
import argparse
import tempfile

# =============================================================================
# 1. OS MODULE - DIRECTORY OPERATIONS
# =============================================================================
print("\n--- 1. OS Module - Directory Operations ---\n")

# Current working directory
cwd = os.getcwd()
print(f"Current directory: {cwd}")

# List directory contents
print(f"Files in current dir: {os.listdir('.')[:5]}...")

# Path operations
path = os.path.join('folder', 'subfolder', 'file.txt')
print(f"Joined path: {path}")

dirname = os.path.dirname('/home/user/file.txt')
basename = os.path.basename('/home/user/file.txt')
print(f"dirname: {dirname}, basename: {basename}")

name, ext = os.path.splitext('document.pdf')
print(f"Name: {name}, Extension: {ext}")

# Check paths
print(f"Home exists: {os.path.exists(os.path.expanduser('~'))}")

# =============================================================================
# 2. OS MODULE - FILE INFO
# =============================================================================
print("\n--- 2. OS Module - File Info ---\n")

# Create a temp file to demonstrate
import tempfile
with tempfile.NamedTemporaryFile(mode='w', delete=False, suffix='.txt') as f:
    f.write("Hello, World!")
    temp_file = f.name

# Get file info
info = os.stat(temp_file)
print(f"File: {temp_file}")
print(f"Size: {info.st_size} bytes")
print(f"Mode: {oct(info.st_mode)}")

# Clean up
os.remove(temp_file)

# =============================================================================
# 3. OS MODULE - ENVIRONMENT VARIABLES
# =============================================================================
print("\n--- 3. OS Module - Environment Variables ---\n")

# Get environment variables
print(f"HOME: {os.environ.get('HOME', 'Not set')}")
print(f"USER: {os.environ.get('USER', 'Not set')}")
print(f"SHELL: {os.environ.get('SHELL', 'Not set')}")

# Set environment variable (for this process only)
os.environ['MY_APP_CONFIG'] = 'production'
print(f"MY_APP_CONFIG: {os.environ.get('MY_APP_CONFIG')}")

# =============================================================================
# 4. OS MODULE - WALK DIRECTORY
# =============================================================================
print("\n--- 4. OS Module - Walk Directory ---\n")

# Create temp directory structure
with tempfile.TemporaryDirectory() as tmpdir:
    # Create structure
    os.makedirs(os.path.join(tmpdir, 'subdir1'))
    os.makedirs(os.path.join(tmpdir, 'subdir2'))
    Path(os.path.join(tmpdir, 'file1.txt')).touch()
    Path(os.path.join(tmpdir, 'subdir1', 'file2.txt')).touch()
    
    # Walk directory
    print("Walking directory:")
    for root, dirs, files in os.walk(tmpdir):
        level = root.replace(tmpdir, '').count(os.sep)
        indent = ' ' * 2 * level
        print(f"{indent}{os.path.basename(root)}/")
        subindent = ' ' * 2 * (level + 1)
        for file in files:
            print(f"{subindent}{file}")

# =============================================================================
# 5. SYS MODULE
# =============================================================================
print("\n--- 5. SYS Module ---\n")

print(f"Python version: {sys.version}")
print(f"Platform: {sys.platform}")
print(f"Python path (first 3): {sys.path[:3]}")
print(f"Recursion limit: {sys.getrecursionlimit()}")

# Object size
list_size = sys.getsizeof([1, 2, 3, 4, 5])
dict_size = sys.getsizeof({'a': 1, 'b': 2})
print(f"\nSize of [1,2,3,4,5]: {list_size} bytes")
print(f"Size of {{'a':1,'b':2}}: {dict_size} bytes")

# Command line args (simulated)
print(f"\nScript name: {sys.argv[0]}")

# =============================================================================
# 6. LOGGING - BASIC
# =============================================================================
print("\n--- 6. Logging - Basic ---\n")

# Reset logging
for handler in logging.root.handlers[:]:
    logging.root.removeHandler(handler)

# Basic configuration
logging.basicConfig(
    level=logging.DEBUG,
    format='%(levelname)s - %(message)s'
)

# Create logger
logger = logging.getLogger('example')

print("Logging at different levels:")
logger.debug("This is a DEBUG message")
logger.info("This is an INFO message")
logger.warning("This is a WARNING message")
logger.error("This is an ERROR message")

# =============================================================================
# 7. LOGGING - TO FILE
# =============================================================================
print("\n--- 7. Logging - To File ---\n")

# Create a file handler
with tempfile.NamedTemporaryFile(mode='w', delete=False, suffix='.log') as f:
    log_file = f.name

# Reset and create new logger
file_logger = logging.getLogger('file_example')
file_logger.setLevel(logging.DEBUG)
file_logger.handlers = []

file_handler = logging.FileHandler(log_file)
file_handler.setFormatter(logging.Formatter('%(asctime)s - %(levelname)s - %(message)s'))
file_logger.addHandler(file_handler)

file_logger.info("Logged to file")
file_logger.warning("Warning logged to file")

# Read log file
print(f"Log file contents ({log_file}):")
print(Path(log_file).read_text())

os.remove(log_file)

# =============================================================================
# 8. LOGGING - EXCEPTION
# =============================================================================
print("\n--- 8. Logging - Exception ---\n")

exc_logger = logging.getLogger('exception_example')
exc_logger.handlers = []
handler = logging.StreamHandler()
handler.setFormatter(logging.Formatter('%(levelname)s - %(message)s'))
exc_logger.addHandler(handler)

try:
    result = 10 / 0
except ZeroDivisionError:
    exc_logger.exception("An error occurred")

# =============================================================================
# 9. ARGPARSE - BASIC
# =============================================================================
print("\n--- 9. Argparse - Basic ---\n")

# Create parser
parser = argparse.ArgumentParser(
    description='Example program demonstrating argparse'
)

# Add arguments
parser.add_argument('--name', default='World', help='Name to greet')
parser.add_argument('-v', '--verbose', action='store_true', help='Verbose output')
parser.add_argument('-n', '--number', type=int, default=1, help='Number of greetings')

# Parse (use known args to avoid error with script args)
args, unknown = parser.parse_known_args(['--name', 'Python', '-v', '-n', '3'])

print(f"Parsed args: {args}")
print(f"Name: {args.name}")
print(f"Verbose: {args.verbose}")
print(f"Number: {args.number}")

if args.verbose:
    for i in range(args.number):
        print(f"Hello, {args.name}!")

# =============================================================================
# 10. ARGPARSE - CHOICES AND TYPES
# =============================================================================
print("\n--- 10. Argparse - Choices and Types ---\n")

parser2 = argparse.ArgumentParser()
parser2.add_argument('--color', choices=['red', 'green', 'blue'], default='blue')
parser2.add_argument('--size', type=float, default=1.0)
parser2.add_argument('--items', nargs='+', help='Multiple items')

args2, _ = parser2.parse_known_args(['--color', 'red', '--items', 'a', 'b', 'c'])

print(f"Color: {args2.color}")
print(f"Size: {args2.size}")
print(f"Items: {args2.items}")

# =============================================================================
# 11. PATHLIB
# =============================================================================
print("\n--- 11. Pathlib ---\n")

# Create path objects
home = Path.home()
current = Path.cwd()

print(f"Home: {home}")
print(f"Current: {current}")

# Path operations
path = Path('/home/user/documents/file.txt')
print(f"\nPath: {path}")
print(f"Parent: {path.parent}")
print(f"Name: {path.name}")
print(f"Stem: {path.stem}")
print(f"Suffix: {path.suffix}")

# Build paths with /
new_path = Path.home() / 'projects' / 'myproject'
print(f"\nBuilt path: {new_path}")

# =============================================================================
# 12. PATHLIB - GLOB
# =============================================================================
print("\n--- 12. Pathlib - Glob ---\n")

# Create temp structure
with tempfile.TemporaryDirectory() as tmpdir:
    tmp_path = Path(tmpdir)
    
    # Create files
    (tmp_path / 'file1.py').write_text('print("hello")')
    (tmp_path / 'file2.py').write_text('print("world")')
    (tmp_path / 'data.txt').write_text('data')
    (tmp_path / 'subdir').mkdir()
    (tmp_path / 'subdir' / 'nested.py').write_text('# nested')
    
    # Glob pattern
    print("Python files in root:")
    for py_file in tmp_path.glob('*.py'):
        print(f"  {py_file.name}")
    
    print("\nAll Python files (recursive):")
    for py_file in tmp_path.rglob('*.py'):
        print(f"  {py_file.relative_to(tmp_path)}")

# =============================================================================
# 13. PATHLIB - READ/WRITE
# =============================================================================
print("\n--- 13. Pathlib - Read/Write ---\n")

with tempfile.TemporaryDirectory() as tmpdir:
    tmp_path = Path(tmpdir)
    
    # Write file
    file_path = tmp_path / 'example.txt'
    file_path.write_text('Hello from pathlib!')
    
    # Read file
    content = file_path.read_text()
    print(f"Content: {content}")
    
    # File info
    print(f"Exists: {file_path.exists()}")
    print(f"Is file: {file_path.is_file()}")
    print(f"Size: {file_path.stat().st_size} bytes")

# =============================================================================
# 14. PRACTICAL EXAMPLE - LOG ANALYZER
# =============================================================================
print("\n--- 14. Practical Example - Log Analyzer ---\n")

def analyze_logs(log_content):
    """Analyze log content and return statistics."""
    levels = {'DEBUG': 0, 'INFO': 0, 'WARNING': 0, 'ERROR': 0, 'CRITICAL': 0}
    
    for line in log_content.split('\n'):
        for level in levels:
            if level in line:
                levels[level] += 1
                break
    
    return levels

# Sample log content
sample_logs = """
2024-01-01 10:00:00 - INFO - Application started
2024-01-01 10:00:01 - DEBUG - Loading config
2024-01-01 10:00:02 - INFO - Config loaded
2024-01-01 10:00:03 - WARNING - Memory usage high
2024-01-01 10:00:04 - ERROR - Failed to connect to database
2024-01-01 10:00:05 - INFO - Retrying connection
2024-01-01 10:00:06 - INFO - Connected successfully
2024-01-01 10:00:07 - DEBUG - Processing request
"""

stats = analyze_logs(sample_logs)
print("Log Statistics:")
for level, count in stats.items():
    if count > 0:
        print(f"  {level}: {count}")

print("\n" + "=" * 60)
print("END OF EXAMPLES")
print("=" * 60)
Examples - Python Tutorial | DeepML