Subprocess, Pandas and Built-in functions
AI agents run shell commands (subprocess), analyze data (pandas), and transform collections (built-ins like sorted, zip, all). These tools appear in every production AI codebase. Let us learn them together.
Python standard library for AI
Three essential tools from the Python ecosystem
import subprocess
# subprocess.run() runs shell commands from Python
# This is how AI agents execute bash commands
result = subprocess.run(
"echo 'Hello from subprocess!'",
shell=True,
capture_output=True, # capture stdout and stderr
text=True, # return strings, not bytes
timeout=10, # safety timeout
)
print(f"stdout: {result.stdout.strip()}")
print(f"returncode: {result.returncode}") # 0 = success
result = subprocess.run(
"python --version",
shell=True, capture_output=True, text=True,
)
print(f"Python version: {result.stdout.strip()}")subprocess.run() executes shell commands from Python. capture_output=True captures the output. text=True returns strings instead of bytes. This is exactly how AI agents run tools.
pandas is used to analyze results from AI queries: viewing data tables, calculating statistics, filtering rows, and preparing data for visualization. When an AI agent runs a SQL query, the results often end up in a pandas DataFrame for analysis.
import pandas as pd
# Create a DataFrame (like a spreadsheet in code)
data = [
{"product": "Mushroom Burger", "price": 12.99, "rating": 4.5},
{"product": "Quinoa Bowl", "price": 10.99, "rating": 4.8},
{"product": "Tofu Tacos", "price": 9.99, "rating": 4.2},
{"product": "Mac & Cheese", "price": 11.99, "rating": 4.6},
]
df = pd.DataFrame(data)
print(df)
print(f"Shape: {df.shape}") # (4 rows, 3 columns)
print(f"Avg price: ${df['price'].mean():.2f}")
print(f"Top rated:\n{df.sort_values('rating', ascending=False).head(2)}")DataFrames are tables in code. .mean() for averages, .sort_values() for sorting, .head() for top N rows.
Beyond pandas, Python has powerful built-in functions that you will use constantly in AI code: sorted() for ranking results, zip() for pairing items, and all()/any() for validation checks.
# sorted() with key= (very common in AI for ranking results)
api_results = [
{"dish": "Quinoa Bowl", "score": 0.88},
{"dish": "Mac & Cheese", "score": 0.53},
{"dish": "Avocado Toast", "score": 0.95},
]
ranked = sorted(api_results, key=lambda x: x["score"], reverse=True)
for r in ranked:
print(f" [{r['score']:.2f}] {r['dish']}")
# zip() pairs up items from multiple lists
questions = ["What is RAG?", "What is an agent?"]
answers = ["Retrieval-Augmented Generation", "An LLM with tools"]
for q, a in zip(questions, answers):
print(f" Q: {q} -> A: {a}")
# all() and any() validate collections
required = ["role", "content"]
message = {"role": "user", "content": "Hello"}
is_valid = all(field in message for field in required)
print(f"Message valid: {is_valid}")sorted() ranks results. zip() pairs up lists. all() checks every condition. These are the Swiss Army knife of Python.
Matching exercise: Match Built-in functions
Loading practiceโฆ
Validation checklist: Subprocess and Built-ins checklist
Loading practiceโฆ