Python Executor

Secure and efficient Python code execution environment for automated script processing and integration

Python Executor is an AI skill that provides secure sandboxed environments for running Python code snippets, scripts, and data processing tasks within AI assistant workflows. It covers sandbox configuration, execution isolation, resource limits, output capture, and dependency management that enable safe code execution as part of automated pipelines.

What Is This?

Overview

Python Executor offers structured approaches to running Python code safely within automated workflows. It handles configuring sandboxed execution environments with restricted system access, managing Python dependencies and virtual environments for consistent execution, enforcing resource limits on CPU time, memory usage, and disk I/O, capturing standard output and error streams for result processing, handling timeouts and graceful termination of long running scripts, and returning structured execution results with output, errors, and exit codes.

Who Should Use This

This skill serves AI assistant developers who need to execute generated code safely, platform teams building code execution services for educational tools, data engineers running transformation scripts in automated pipelines, and developers creating interactive coding environments with execution capabilities.

Why Use It?

Problems It Solves

Running untrusted Python code without isolation risks system compromise through file system access or network calls. Without resource limits, a single script can consume all available memory or CPU, affecting other services. Capturing execution output requires careful stream handling to avoid deadlocks. Managing dependencies for each execution context adds complexity that slows down script processing.

Core Highlights

Sandbox isolation prevents executed code from accessing the host system beyond defined boundaries. Resource limits cap memory and CPU usage to prevent runaway scripts. Output capture collects stdout, stderr, and return values in structured format. Dependency management installs required packages in isolated virtual environments.

How to Use It?

Basic Usage

import subprocess
import tempfile
import os
from dataclasses import dataclass

@dataclass
class ExecutionResult:
    stdout: str
    stderr: str
    exit_code: int
    timed_out: bool

class PythonExecutor:
    def __init__(self, timeout=30, max_memory_mb=256):
        self.timeout = timeout
        self.max_memory = max_memory_mb

    def execute(self, code, env_vars=None):
        with tempfile.NamedTemporaryFile(
            suffix=".py", mode="w", delete=False
        ) as f:
            f.write(code)
            script_path = f.name
        try:
            env = os.environ.copy()
            if env_vars:
                env.update(env_vars)
            proc = subprocess.run(
                ["python3", script_path],
                capture_output=True, text=True,
                timeout=self.timeout, env=env
            )
            return ExecutionResult(
                stdout=proc.stdout,
                stderr=proc.stderr,
                exit_code=proc.returncode,
                timed_out=False
            )
        except subprocess.TimeoutExpired:
            return ExecutionResult(
                stdout="", stderr="Execution timed out",
                exit_code=-1, timed_out=True
            )
        finally:
            os.unlink(script_path)

Real-World Examples

import resource
import signal

class SandboxedExecutor:
    def __init__(self, config):
        self.config = config

    def set_limits(self):
        mem_bytes = self.config["max_memory_mb"] * 1024 * 1024
        resource.setrlimit(
            resource.RLIMIT_AS, (mem_bytes, mem_bytes)
        )
        cpu_seconds = self.config["max_cpu_seconds"]
        resource.setrlimit(
            resource.RLIMIT_CPU, (cpu_seconds, cpu_seconds)
        )

    def execute_sandboxed(self, code):
        safe_globals = {
            "__builtins__": {
                "print": print, "range": range,
                "len": len, "str": str, "int": int,
                "float": float, "list": list,
                "dict": dict, "enumerate": enumerate,
                "zip": zip, "map": map, "sum": sum,
                "min": min, "max": max, "sorted": sorted,
            }
        }
        self.set_limits()
        output = []
        safe_globals["__builtins__"]["print"] = (
            lambda *args: output.append(
                " ".join(str(a) for a in args)
            )
        )
        exec(code, safe_globals)
        return "\n".join(output)

Advanced Tips

Use separate virtual environments for each execution context to prevent dependency conflicts between scripts. Set both soft and hard resource limits so scripts receive a warning signal before forced termination. Log execution metrics including duration and memory peak for capacity planning and abuse detection.

When to Use It?

Use Cases

Use Python Executor when building AI assistants that need to run generated Python code, when creating educational platforms with interactive code execution, when processing user-submitted data transformation scripts in pipelines, or when testing code snippets in isolated environments before deployment.

Related Topics

Container based isolation with Docker, process sandboxing with seccomp, virtual environment management, subprocess handling in Python, and code execution security practices complement Python execution workflows.

Important Notes

Requirements

Python runtime installed in the execution environment. Operating system support for resource limits such as Linux rlimit. Sufficient isolation mechanisms to prevent unauthorized system access from executed code.

Usage Recommendations

Do: always set timeouts and memory limits before executing any code to prevent resource exhaustion. Restrict the builtins available to executed code by removing file I/O and network functions. Log all execution attempts with the code submitted for security auditing.

Don't: execute untrusted code with full system access, even briefly for testing. Allow executed scripts to import arbitrary modules without an explicit allowlist. Trust exit codes alone as success indicators without examining stderr for warnings.

Limitations

Python level sandboxing with restricted builtins can be bypassed by determined attackers and should not be the sole isolation layer. Resource limits vary by operating system and may not be available on all platforms. Complex scripts with external dependencies require pre-built environments that add setup overhead.