Welcome to the Python Interview Guide. This document covers essential libraries, scripting scenarios, and data parsing tasks relevant to DevOps.
| Type | Syntax | Ordered? | Mutable? | Unique? | Use Case |
|---|---|---|---|---|---|
| List | [1, 2, 2] |
Yes | Yes | No | Ordered sequence (Log lines). |
| Set | {1, 2} |
No | Yes | Yes | Collecting unique IPs (Deduplication). |
| Tuple | (1, 2) |
Yes | No | No | Fixed Configuration (Coordinates). |
| Dict | {'k': 'v'} |
Yes (3.7+) | Yes | Keys | Looking up values (JSON, Environment Variables). |
Philosophy: "Fail Gracefully." Don't let the script crash with a stack trace; print a helpful message.
import sys
try:
with open("config.yaml") as f:
content = f.read()
except FileNotFoundError:
print("Error: config.yaml not found. Please create it.")
sys.exit(1) # Exit with non-zero status code
except PermissionError:
print("Error: Permission denied reading config.")
sys.exit(1)Definition: Boto3 is the AWS SDK for Python. It allows you to create, update, and delete AWS resources programmatically.
Example: List S3 Buckets
import boto3
# Create a client (uses ~/.aws/credentials)
s3 = boto3.client('s3')
response = s3.list_buckets()
print("Buckets:")
for bucket in response['Buckets']:
print(f"- {bucket['Name']}")Scenario: Check if a website is up.
import requests
try:
resp = requests.get('https://api.github.com', timeout=5)
if resp.status_code == 200:
print("API is Up!")
else:
print(f"API returned {resp.status_code}")
except requests.exceptions.Timeout:
print("Request Timed Out.")Task: "Given a remote log file, find all 404 errors."
import requests
LOG_URL = "https://example.com/access.log"
def analyze_logs():
r = requests.get(LOG_URL)
# Iterate line by line
for line in r.text.splitlines():
# Simple string check (faster than Regex for simple cases)
if ' 404 ' in line:
print(f"Broken Link Found: {line}")
if __name__ == "__main__":
analyze_logs()Task: "Use the Docker SDK to run an Nginx container."
import docker
# Connect to local Docker socket
client = docker.from_env()
try:
print("Pulling Nginx Image...")
client.images.pull("nginx:latest")
print("Starting Container...")
container = client.containers.run(
"nginx:latest",
detach=True,
ports={'80/tcp': 8080},
name="my-web-server"
)
print(f"Started container {container.short_id}")
except docker.errors.APIError as e:
print(f"Docker Error: {e}")Task: "Get the ID of all Running instances from this JSON."
import json
raw_response = '''
{
"instances": [
{"id": "i-123", "state": "running", "type": "t2.micro"},
{"id": "i-456", "state": "stopped", "type": "m5.large"},
{"id": "i-789", "state": "running", "type": "t2.micro"}
]
}
'''
data = json.loads(raw_response)
# List Comprehension (Pythonic way)
running_ids = [
inst['id']
for inst in data['instances']
if inst['state'] == 'running'
]
print(f"Running Instances: {running_ids}")