跳转到主要内容

Run Python code

import { PackageManagers, Render, Steps, TypeScriptExample, WranglerConfig, } from "~/components";

Run Python code in a sandbox and return its output. The image sets the Python version and the packages the code can import. Files that one run writes stay in the sandbox for the next run.

Prerequisites

Run Python code

1. Create a file named `sales.py` with the Python code to run. In this example, the code uses `pandas`:
import pandas as pd

sales = pd.DataFrame({"city": ["Lisbon", "Austin", "Lisbon"], "units": [3, 5, 4]})
print(sales.groupby("city")["units"].sum())
  1. Create a Dockerfile in your project root with Python and the packages the code can import:

    FROM python:3.13-slim
    
    RUN pip install --no-cache-dir numpy pandas matplotlib
    
    WORKDIR /workspace
    
    CMD ["sleep", "infinity"]
    

    Installing packages in the image makes them available as soon as the sandbox starts, without Internet access in the sandbox.

  2. In wrangler.jsonc, build the Dockerfile as a named image in your containers entry, then generate types:

    {
    	"containers": [
    		{
    			"class_name": "MyContainer",
    			"scheduling_policy": "durable_object",
    			"images": {
    				"python": {
    					"dockerfile": "./Dockerfile",
    				},
    			},
    		},
    	],
    }
    
  3. Add an inactivity timeout to your Durable Object. The constructor sets the timeout again when a restarted Durable Object finds the container running:

    const INACTIVITY_TIMEOUT_MS = 10 * 60 * 1000;
    
    export class MyContainer extends DurableObject<Env> {
    	constructor(ctx: DurableObjectState, env: Env) {
    		super(ctx, env);
    		const container = ctx.container;
    		if (container?.running) {
    			void ctx.blockConcurrencyWhile(() =>
    				container.setInactivityTimeout(INACTIVITY_TIMEOUT_MS),
    			);
    		}
    	}
    }
    

    Then add a method that runs Python code:

    export class MyContainer extends DurableObject<Env> {
    	// ...
    
    	async runPython(code: string) {
    		const container = this.ctx.container;
    
    		if (!container) {
    			throw new Error("No container is configured");
    		}
    
    		if (!container.running) {
    			container.start({
    				image: container.images.python,
    				// Block the code from reaching the Internet
    				enableInternet: false,
    			});
    			await container.setInactivityTimeout(INACTIVITY_TIMEOUT_MS);
    		}
    
    		// Each run is a new Python process, so variables do not carry over
    		const process = await container.exec(
    			[
    				// GNU coreutils `timeout` stops code that runs longer than 60 seconds
    				"timeout", "--kill-after=5", "60",
    				// `python3 -` reads the code from standard input
    				"python3", "-",
    			],
    			{
    				stdin: new Response(code).body!,
    				// Files that the code writes here stay until the instance stops
    				cwd: "/workspace",
    			},
    		);
    		const output = await process.output();
    		const decoder = new TextDecoder();
    
    		return {
    			stdout: decoder.decode(output.stdout),
    			// A Python exception prints its traceback here
    			stderr: decoder.decode(output.stderr),
    			// `124` or `137` if the code timed out, `1` if it raised an exception
    			exitCode: output.exitCode,
    		};
    	}
    }
    

    For how timeout stops the processes that the code starts, refer to Stop the processes a command starts.

    output() holds everything the code prints in the memory of the Durable Object. For code that prints a lot, stream the output instead.

  4. Add a route to your Worker that runs the request body as Python code:

    export default {
    	async fetch(request: Request, env: Env): Promise<Response> {
    		const url = new URL(request.url);
    		const match = /^\/sandboxes\/([a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)\/python$/.exec(url.pathname);
    
    		if (!match || request.method !== "POST") {
    			return new Response("Not found", { status: 404 });
    		}
    
    		const sandbox = env.MY_CONTAINER.getByName(match[1]);
    		return Response.json(await sandbox.runPython(await request.text()));
    	},
    } satisfies ExportedHandler<Env>;
    

    The code can read every file in its sandbox, so give each user their own sandbox name, and authenticate callers first. For more information, refer to Sandbox security.

  5. Deploy your Worker:

  6. Run sales.py in a sandbox named ada. Replace the example hostname with the workers.dev URL that Wrangler prints:

    curl https://<YOUR_WORKER>.<YOUR_SUBDOMAIN>.workers.dev/sandboxes/ada/python --data-binary @sales.py
    
    {
    	"stdout": "city\nAustin    5\nLisbon    7\nName: units, dtype: int64\n",
    	"stderr": "",
    	"exitCode": 0
    }
    

Return a chart

To return an image, such as a matplotlib chart, have the code save it in /workspace, then read the file in another request:

  1. Add a method to your Durable Object that reads a file from /workspace:

    export class MyContainer extends DurableObject<Env> {
    	// ...
    
    	async readFile(name: string) {
    		const container = this.ctx.container;
    
    		if (!container?.running) {
    			return null;
    		}
    
    		const process = await container.exec(["cat", "--", name], {
    			cwd: "/workspace",
    			stderr: "ignore",
    		});
    		const output = await process.output();
    		return output.exitCode === 0 ? output.stdout : null;
    	}
    }
    
  2. In the fetch() handler of your Worker, after the line that parses url, add a route that returns the chart:

    const chart = /^\/sandboxes\/([a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)\/chart\.png$/.exec(url.pathname);
    
    if (chart) {
    	const png = await env.MY_CONTAINER.getByName(chart[1]).readFile("chart.png");
    	return png
    		? new Response(png, { headers: { "Content-Type": "image/png" } })
    		: new Response("Not found", { status: 404 });
    }
    
  3. Run code that saves a chart, then open /sandboxes/ada/chart.png in your browser:

    import matplotlib
    
    matplotlib.use("Agg")
    import matplotlib.pyplot as plt
    
    plt.bar(["Austin", "Lisbon"], [5, 7])
    plt.savefig("chart.png")
    
    curl https://<YOUR_WORKER>.<YOUR_SUBDOMAIN>.workers.dev/sandboxes/ada/python --data-binary @chart.py
    

    matplotlib.use("Agg") draws without a display. For larger files and uploads, refer to Move files in and out of a sandbox.

Run another language

To run another language, change the base image and the command that reads standard input. For example, use FROM ruby:3.4-slim and ["ruby", "-"], or FROM node:24-slim and ["node", "-"].