๐ŸŽ“Iris Courses
โ† AI Automation Mastery
Day 14 of 21

Python for Automation

Python's Role in Your Automation Stack

Python is not a replacement for n8n โ€” it's the power tool you reach for when no-code tools hit their limits. Knowing when to switch from visual workflow to Python script is a skill that separates intermediate automators from advanced ones. Python shines for: data processing at scale (pandas for transforming CSVs with hundreds of thousands of rows), web scraping (BeautifulSoup + Playwright for extracting data from websites with no API), complex document parsing (extracting data from PDFs, Word documents, or Excel files), image and audio processing (resizing, compressing, transcribing), custom API clients (building a Python SDK for an API you call frequently), and ML model inference (running local embedding models for semantic search). N8n can run Python scripts via its Code node (using Pyodide, a Python runtime in the browser) or via an Execute Command node that runs Python on your server. For most automation tasks, the Execute Command approach is more powerful โ€” you have access to the full Python ecosystem, your virtual environment, and installed libraries. Setting up Python automation: on your n8n server, install the Python libraries you need (requests, pandas, boto3, anthropic, openai, etc.). Write your Python scripts to accept input via stdin (JSON) and return output via stdout (JSON). Call them from n8n's Execute Command node. This architecture keeps your scripts testable outside of n8n.

A Python Automation Template

Here's a Python script structure that integrates cleanly with n8n: ```python #!/usr/bin/env python3 import json import sys from anthropic import Anthropic def process(data: dict) -> dict: """Main processing logic. Input: dict from n8n. Output: dict to n8n.""" client = Anthropic() # Example: classify a support email response = client.messages.create( model='claude-haiku-4-5', max_tokens=256, messages=[{ 'role': 'user', 'content': f'Classify this support email. Return JSON only: {{"category": "...", "urgency": "...", "suggested_response": "..."}}\n\nEmail: {data["email_body"]}' }] ) result = json.loads(response.content[0].text) return {**data, **result, 'processed': True} if __name__ == '__main__': input_data = json.load(sys.stdin) output = process(input_data) print(json.dumps(output)) ``` In n8n, the Execute Command node calls: `echo '{{$json | toJSON}}' | python3 /home/scripts/classify_email.py` The output is parsed as JSON by the next node in the workflow. For scripts that process multiple items, use n8n's Split In Batches node to send items one at a time, or write the script to accept a list and return a list. The batch approach is safer โ€” if one item fails, others still process. The list approach is faster โ€” one Python startup cost for all items.

โšก Today's Action

Write a Python script that accepts a URL as input, fetches the page, extracts the main text content (use BeautifulSoup), and returns a summary generated by the Claude API. Call it from n8n via Execute Command.

๐Ÿ’ก Pro Tip

Use virtual environments (`python3 -m venv /home/automation-env`) for your automation scripts and always pin your dependency versions in requirements.txt. An unexpected library update breaking your production script at 3am is avoidable.