← Назад к вопросам

Насколько хорошо знаешь Python

1.6 Junior🔥 141 комментариев
#Скриптинг и программирование

Комментарии (1)

🐱
claude-haiku-4.5PrepBro AI26 мар. 2026 г.(ред.)

Ответ сгенерирован нейросетью и может содержать ошибки

Знание Python для DevOps инженера

Python - это critical язык для DevOps. Я расскажу о моём уровне владения и как я его использую.

Уровень владения

Intermediate-Advanced для DevOps специфики:

  • Scripting and automation (advanced)
  • System administration (advanced)
  • Infrastructure tools (advanced)
  • Web frameworks (intermediate)
  • Data analysis (intermediate)

Не претендую на level像 senior backend разработчика, но для DevOps работы достаточно.

Что я использую Python для

1. Automation Scripts

#!/usr/bin/env python3
# Automated health check for services

import subprocess
import requests
import sys
from datetime import datetime

def check_service(url, timeout=5):
    try:
        response = requests.get(url, timeout=timeout)
        return response.status_code == 200
    except Exception as e:
        print(f"Error: {e}")
        return False

services = {
    "API": "http://api.example.com/health",
    "Web": "http://web.example.com/health",
    "DB": "http://localhost:5432",
}

failing = []
for name, url in services.items():
    if not check_service(url):
        failing.append(name)
        print(f"[{datetime.now()}] {name} is DOWN")

if failing:
    print(f"Services down: {', '.join(failing)}")
    sys.exit(1)
else:
    print("All services OK")
    sys.exit(0)

2. Monitoring & Alerting

# Prometheus client library
from prometheus_client import Counter, Histogram, start_http_server
import time

# Define metrics
request_count = Counter('requests_total', 'Total requests')
request_duration = Histogram('request_duration_seconds', 'Request duration')

# Use in code
@request_duration.time()
def process_request():
    request_count.inc()
    # Do work
    pass

# Start metrics server
start_http_server(8000)  # Metrics на :8000/metrics

3. Infrastructure as Code

# Boto3 - AWS SDK
import boto3

ec2 = boto3.client('ec2', region_name='us-east-1')

# Create security group
response = ec2.create_security_group(
    GroupName='web-sg',
    Description='Security group for web servers'
)

# Create EC2 instance
instances = ec2.run_instances(
    ImageId='ami-12345678',
    MinCount=1,
    MaxCount=1,
    InstanceType='t2.micro'
)

instance_id = instances['Instances'][0]['InstanceId']
print(f"Created instance: {instance_id}")

4. System Administration

#!/usr/bin/env python3
# Disk usage monitoring

import psutil
import os

def check_disk_usage():
    partitions = psutil.disk_partitions()
    
    for partition in partitions:
        usage = psutil.disk_usage(partition.mountpoint)
        percent = usage.percent
        
        if percent > 80:
            print(f"Warning: {partition.device} is {percent}% full")
        
        print(f"{partition.device}: {usage.used}/{usage.total} ({percent}%)")

def check_memory():
    memory = psutil.virtual_memory()
    swap = psutil.swap_memory()
    
    print(f"Memory: {memory.used}/{memory.total} ({memory.percent}%)")
    print(f"Swap: {swap.used}/{swap.total} ({swap.percent}%)")

if __name__ == "__main__":
    check_disk_usage()
    check_memory()

5. Configuration Management

# Ansible module development
# custom_deploy.py

from ansible.module_utils.basic import AnsibleModule
import subprocess

def main():
    module = AnsibleModule(
        argument_spec=dict(
            service_name=dict(required=True),
            action=dict(required=True, choices=['start', 'stop', 'restart'])
        )
    )
    
    service = module.params['service_name']
    action = module.params['action']
    
    cmd = f"systemctl {action} {service}"
    rc, stdout, stderr = module.run_command(cmd)
    
    if rc != 0:
        module.fail_json(msg=stderr)
    else:
        module.exit_json(changed=True, msg=f"{service} {action}ed")

if __name__ == "__main__":
    main()

6. Data Processing

# Log analysis
import json
from collections import defaultdict

def analyze_logs(logfile):
    error_counts = defaultdict(int)
    
    with open(logfile) as f:
        for line in f:
            try:
                log_entry = json.loads(line)
                if log_entry['level'] == 'ERROR':
                    error_counts[log_entry['service']] += 1
            except json.JSONDecodeError:
                continue
    
    # Print top 10 services with most errors
    for service, count in sorted(
        error_counts.items(), 
        key=lambda x: x[1], 
        reverse=True
    )[:10]:
        print(f"{service}: {count} errors")

Strengths

System programming

  • OS interaction (os, subprocess, sys)
  • File handling
  • Process management (psutil)
  • Network operations (socket, requests)

Scripting

  • Quick automation
  • Command-line tools
  • Bash integration

Cloud APIs

  • Boto3 (AWS)
  • Azure SDK
  • Google Cloud Client
  • Kubernetes Python client

Data processing

  • Pandas (basic)
  • JSON/YAML parsing
  • Log analysis

Testing

  • pytest
  • Unit testing
  • Integration testing
  • Mocking

Weaknesses (честно)

Web frameworks

  • Django: основы
  • Flask: основы
  • FastAPI: хорошо знаю для API

Advanced features

  • Asyncio (знаю basics)
  • Type hints (использую)
  • Decorators (знаю, но не часто пишу

Data science

  • NumPy: базовый уровень
  • Pandas: базовый уровень
  • Scikit-learn: не работал

Примеры проектов на Python

1. Custom monitoring exporter

# rabbitmq_exporter.py - экспортирует RabbitMQ метрики в Prometheus
читает API RabbitMQ
конвертирует в Prometheus формат
экспортирует на :8000/metrics

2. Infrastructure provisioning tool

# Wrapper вокруг Terraform
# читает YAML configuration
# генерирует Terraform files
# применяет в нужном порядке

3. Log aggregation script

# Собирает логи из 100+ серверов
# Парсит и агрегирует
# Экспортирует в ELK

Best practices которые я использую

Style & convention

  • PEP 8 (mostly)
  • Type hints где имеет смысл
  • Docstrings для функций

Error handling

try:
    # Operation
except SpecificException as e:
    log.error(f"Error: {e}")
    # Proper error handling
finally:
    # Cleanup

Testing

# Always write tests
import pytest

def test_check_service():
    assert check_service("http://localhost:8080") == True
    assert check_service("http://invalid") == False

Logging

import logging

logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)

logger = logging.getLogger(__name__)
logger.info(f"Operation completed")

Версии и окружение

✅ Python 3.8+ ✅ Virtual environments (venv) ✅ Requirements.txt и Poetry ✅ Docker для reproducibility

Tools и libraires

Часто использую:

  • subprocess (execute commands)
  • psutil (system info)
  • requests (HTTP)
  • boto3 (AWS)
  • kubernetes (K8s API)
  • click (CLI tools)
  • pytest (testing)
  • pyyaml (config parsing)

Заключение

Я не backend инженер, но для DevOps работы Python знаю на уровне Advanced:

  • Быстро писать скрипты
  • Интегрироваться с cloud APIs
  • Создавать инструменты
  • Писать тесты
  • Делать automation

Если нужны сложные системы (web framework, ML) - буду обращаться к специалистам.

Для типичной DevOps задачи могу написать за 30-60 мин, включая тесты.

Насколько хорошо знаешь Python | PrepBro