#Python for Scripting
Python excels at automation scripts that are too complex for Bash.
#When to Use Python Over Bash
| Use Python When | Use Bash When |
|---|---|
| Complex logic | Simple commands |
| API interactions | File operations |
| Data processing | Text manipulation |
| Cross-platform | Linux-only |
| Error handling needs | Quick one-liners |
#Script Template
python
1#!/usr/bin/env python3
2"""
3Script: deploy.py
4Description: Automated deployment script
5"""
6
7import argparse
8import logging
9import sys
10from datetime import datetime
11
12# Configure logging
13logging.basicConfig(
14 level=logging.INFO,
15 format='%(asctime)s - %(levelname)s - %(message)s'
16)
17logger = logging.getLogger(__name__)
18
19
20def parse_args():
21 parser = argparse.ArgumentParser(description='Deployment script')
22 parser.add_argument('environment', choices=['staging', 'production'])
23 parser.add_argument('--version', default='latest')
24 parser.add_argument('--dry-run', action='store_true')
25 return parser.parse_args()
26
27
28def deploy(environment: str, version: str, dry_run: bool = False):
29 """Execute deployment."""
30 logger.info(f"Deploying {version} to {environment}")
31
32 if dry_run:
33 logger.info("Dry run - no changes made")
34 return
35
36 # Deployment logic here
37 logger.info("Deployment complete!")
38
39
40def main():
41 args = parse_args()
42
43 try:
44 deploy(args.environment, args.version, args.dry_run)
45 except Exception as e:
46 logger.error(f"Deployment failed: {e}")
47 sys.exit(1)
48
49
50if __name__ == "__main__":
51 main()#Common Patterns
#Subprocess for Commands
python
1import subprocess
2
3# Run command
4result = subprocess.run(
5 ["ls", "-la"],
6 capture_output=True,
7 text=True,
8 check=True
9)
10print(result.stdout)
11
12# Shell command
13result = subprocess.run(
14 "echo $HOME",
15 shell=True,
16 capture_output=True,
17 text=True
18)#HTTP Requests
python
1import requests
2
3# GET
4response = requests.get("https://api.github.com/users/octocat")
5data = response.json()
6
7# POST
8response = requests.post(
9 "https://api.example.com/deploy",
10 json={"version": "1.0.0"},
11 headers={"Authorization": "Bearer token"}
12)#File Operations
python
1from pathlib import Path
2
3# Read/write
4config = Path("config.yaml").read_text()
5Path("output.txt").write_text("Hello")
6
7# List files
8for file in Path("/var/log").glob("*.log"):
9 print(file.name)#Summary
Python is ideal for:
- Complex automation requiring maintainability
- API integrations
- Data processing and transformation
- Cross-platform scripts