DEV Community

qing
qing

Posted on

Deep Python Automation: From Scripts to Production Systems

Deep Python Automation: From Scripts to Production Systems

Python automation can save you hours every day. Here's how to build robust automation systems.

File System Automation

import os
import shutil
from pathlib import Path
from datetime import datetime
import watchdog.observers as observers
import watchdog.events as events

class FileOrganizer(events.FileSystemEventHandler):
    def __init__(self, watch_dir: str):
        self.watch_dir = Path(watch_dir)
        self.rules = {
            '.pdf': 'documents/pdfs',
            '.jpg': 'images/photos', 
            '.png': 'images/screenshots',
            '.mp4': 'videos',
            '.py': 'code/python',
            '.csv': 'data/csv',
        }

    def on_created(self, event):
        if event.is_directory:
            return
        self._organize_file(Path(event.src_path))

    def _organize_file(self, file_path: Path):
        ext = file_path.suffix.lower()
        if ext in self.rules:
            dest_dir = self.watch_dir / self.rules[ext]
            dest_dir.mkdir(parents=True, exist_ok=True)
            dest = dest_dir / file_path.name
            if not dest.exists():
                shutil.move(str(file_path), str(dest))
                print(f"Moved: {file_path.name} โ†’ {self.rules[ext]}/")

# Web scraping automation
import httpx
import asyncio
from bs4 import BeautifulSoup

async def scrape_prices(urls: list) -> dict:
    results = {}
    async with httpx.AsyncClient() as client:
        tasks = [client.get(url) for url in urls]
        responses = await asyncio.gather(*tasks, return_exceptions=True)

        for url, response in zip(urls, responses):
            if isinstance(response, Exception):
                results[url] = {"error": str(response)}
                continue
            soup = BeautifulSoup(response.text, 'html.parser')
            price = soup.select_one('.price')
            results[url] = {"price": price.text if price else "N/A"}

    return results

# Email automation
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

def send_report(to_email: str, subject: str, data: dict):
    msg = MIMEMultipart('alternative')
    msg['Subject'] = subject
    msg['From'] = 'automation@myapp.com'
    msg['To'] = to_email

    html = f"<h1>Report</h1><pre>{data}</pre>"
    msg.attach(MIMEText(html, 'html'))

    with smtplib.SMTP_SSL('smtp.gmail.com', 465) as server:
        server.login(os.getenv('EMAIL'), os.getenv('EMAIL_PASSWORD'))
        server.send_message(msg)
Enter fullscreen mode Exit fullscreen mode

Follow me for more automation tips! ๐Ÿ

Follow for more Python content!


๐Ÿ’ก Related: **Content Creator Ultimate Bundle (Save 33%)* โ€” $29.99*

Top comments (0)