TL;DR
- A Python sandbox for untrusted code has to stop four things: reading files it should not see, reaching the network, eating the machine’s CPU and memory, and leaving changes behind.
- Restricting Python from inside the interpreter does not hold. The Python docs say overriding
__builtins__“is not a security mechanism”, and the author of pysandbox called his own project “broken by design”. - A virtual environment separates packages, and the code in it still runs with your user’s permissions, files and network.
- WebAssembly (Pyodide in the browser, Wasmtime on servers) and containers each draw a real boundary. WebAssembly needs special builds of native packages and cannot start subprocesses, and every container on a host or VM shares one kernel.
- A microVM gives the script a kernel of its own inside a standard Linux system, so pandas and the sqlite3 CLI work as they are. With VirtX, one Python call boots one with no network and a memory cap, and each command runs with a time limit. The run below tests files, network, memory and time.
Python makes it easy to run a string as code: exec() takes one and runs it. That ease is why so many products now run Python that nobody on the team wrote, from code a customer pastes into a form to the scripts an AI agent writes to answer a question.
This post follows one such case and asks where that code should run. You will learn what a Python sandbox has to block, why the in-process approaches fail, what venv, WebAssembly and containers each isolate, and how to run agent-written Python in a disposable microVM with VirtX.
What a Python sandbox has to stop when an agent writes the code
A Python sandbox is a place where code can run without reaching anything you did not hand it. For code an AI agent wrote, that place has to block access to your files and secrets, block or limit the network, cap CPU, memory and run time, and throw away whatever the code changed when it ends.
Suppose we have a small analytics product where users upload a CSV and ask questions in plain English. A model reads the question, writes a short Python script, and the product runs it and shows the answer. Nobody reads the script before it runs.
Most of those scripts will be fine. The ones that are not tend to fall into four groups:
- Reading what it should not: opening
~/.aws/credentials, an .env file or another user’s upload. - Talking to the outside: sending that data to an address on the internet, or downloading something to run next.
- Using up the machine: a
while Trueloop, a list that grows until memory runs out, a fork bomb. - Leaving things behind: a changed file, an installed package or a background process that outlives the run.
A model can write any of these by mistake, or because a user’s prompt or a document it read told it to. The rest of this post looks at where each approach draws its boundary and what that leaves open, starting with the one most people try first.
Why restricting Python inside the interpreter keeps failing
Restricting Python from inside the same interpreter, by removing builtins or filtering names before exec(), does not make a sandbox. Python’s introspection lets code walk from almost any object back to the modules you tried to hide, and the people who built such sandboxes have said so in public.
The Python documentation puts a warning under exec(): “Calling it with untrusted user-supplied input will lead to security vulnerabilities”, and overriding __builtins__ to restrict names “is not a security mechanism”, since the code can still reach all builtins. Victor Stinner, a CPython core developer, spent three years on pysandbox and then wrote that he was “convinced that pysandbox is broken by design”, because “there are too many ways to escape the untrusted namespace using the various introspection features of the Python language.”
RestrictedPython, a library from the Zope project that compiles code with limits on what it may call, is clear about its scope: its documentation says “RestrictedPython is not a sandbox system or a secured environment”. It helps define a trusted environment to run untrusted code in, but that environment is still the interpreter itself. For a script a model wrote, the boundary has to sit outside it.
What a virtual environment leaves open to untrusted code
A virtual environment isolates Python packages, and nothing else. Code inside a venv runs as your user, with your files, your environment variables and your network, so it gives no protection against a script that sets out to read or send something.
The Python docs explain venv as a way to create environments “each with their own independent set of Python packages installed in their site directories”. That is a fix for version conflicts between projects. It does nothing at the operating system level, so the code still runs with every permission the process has.
In the analytics example, a venv keeps the model’s pip install from breaking the product’s own packages, and that is all. The script could still open any file the product’s user can open. The next three approaches put a real wall around the code, each at a different layer.
Running Python in WebAssembly with Pyodide or Wasmtime
WebAssembly runs a CPython interpreter compiled to Wasm inside a sandbox with no direct access to the host’s files or system calls. Pyodide brings it to the browser and Node.js, and WASI runtimes such as Wasmtime run it as a standalone program on a server. The limits for agent code sit in the software around the interpreter, which has to be rebuilt for WebAssembly first.
WebAssembly started in the browser and now runs well beyond it. Wasmtime is a standalone runtime for WebAssembly, WASI and the Component Model, and CPython has supported WASI as a build target since Python 3.11, with PEP 816 setting how that support is versioned from Python 3.15. In every host, WebAssembly’s security model keeps each module in a sandbox, with its memory apart from the runtime’s.
The gaps show up in the packages and tools an agent reaches for:
- Native packages: libraries with compiled C code, such as pandas or NumPy, need wheels built for that WebAssembly target. Pyodide installs pure Python wheels from PyPI. A package with native code needs a Pyodide build, either from Pyodide’s own builds or as a pyemscripten wheel, the platform tag that PEP 783, accepted in April 2026, asks package indexes such as PyPI to accept.
- Dynamic linking: Python loads native extensions as shared libraries at runtime, and each WebAssembly toolchain still handles that its own way. Until Wasmer added dynamic linking to WASIX in February 2026, WASIX could not load shared libraries, which was part of what kept Python’s native modules from running there.
- Subprocesses: on WebAssembly platforms, process APIs such as fork() are unavailable and subprocess imports but does not work, so a script cannot call an existing Linux tool like sqlite3 or ffmpeg.
For a fixed set of pure Python snippets, those limits rarely get in the way. An agent decides what it needs while it runs, so nobody can promise ahead of time that every package and tool it reaches for has a WebAssembly build.
How containers fence Python in at the host kernel
A container runs the script as an ordinary Linux process that the host kernel fences in with namespaces and cgroups. It blocks files and network well when configured with care, and it still shares one kernel with the host and every other container, so a kernel flaw is a way out.
Docker’s security guide calls namespaces the first and most straightforward form of isolation, and lists the kernel’s own security, with its support for namespaces and cgroups, as one of the four areas that decide how safe a container is. Our post on microVMs versus containers follows a break-out through both designs step by step.
On a Mac or Windows laptop, Docker Desktop runs containers inside a Linux VM, so the laptop’s own kernel is already out of reach. The boundary between containers stays the same on every host: all the containers in that VM share one Linux kernel, so a flaw reached from one container reaches every other one, while each microVM gets a kernel of its own.
gVisor was built for untrusted workloads, and Modal’s sandboxes run on it by default. It is an application kernel with a Linux-like interface that intercepts the program’s system calls and serves them itself, so a flaw in the host kernel is much harder to reach. The trade-offs come from the same design:
- It implements a subset of the Linux system call interface, so a program that depends on a missing call can fail, and the only sure test is to run it.
- Work bound by system calls pays for the interception, while compute-bound work pays no such cost.
- It runs on Linux hosts, so on a laptop it sits inside the same kind of Linux VM as Docker Desktop’s containers.
For code nobody has read, which may need any package or tool, the next option keeps a full Linux system and gives every sandbox a kernel of its own.
A microVM gives agent-written Python its own kernel
A microVM is a small virtual machine with its own Linux kernel and only the few virtual devices a job needs, so it boots in a fraction of the time a full VM takes. Code inside it reaches the host only through the hypervisor, the layer that runs virtual machines on the processor’s hardware support.
For the four groups from the start, that gives:
- Files: the script sees the VM’s own disk and whatever you copy or mount in. Your home directory is on another kernel.
- Network: the VM’s network can be cut entirely, so a request has no route out.
- Resources: the VM has a fixed number of CPUs and a fixed amount of memory, and a run can be given a time limit.
- Leftovers: removing the VM removes everything the script wrote.
The cost is a kernel boot per sandbox and the memory for a second kernel. In return the guest is an ordinary Linux system, so the script can pip install a package with native code or call any command-line tool in the image, with no special build. What a microVM is and how it boots goes through what a microVM leaves out to start quickly.
Comparing six ways to sandbox Python code
The table below sums up the approaches above by where the boundary sits, what code can reach in files and network, and which native packages and subprocesses still work. It is our summary from the sources linked in each section, and it assumes each tool is set up with care.
| Approach | Where the boundary sits | Your files | Network | Native packages and subprocesses | Fits |
|---|---|---|---|---|---|
Restricted exec() |
Inside the interpreter | Reachable | Reachable | Yes | Nothing untrusted |
| venv | None, packages only | Reachable | Reachable | Yes | Separating project dependencies |
| WebAssembly (Pyodide, Wasmtime) | The WebAssembly sandbox | Only what the host grants | Limited, set by the host | Needs Wasm builds, no subprocesses | A fixed, pure Python stack |
| Container | The host kernel, shared by every container | Only what you mount | Can be cut | Yes | Code you mostly trust |
| gVisor | gVisor’s application kernel, on a Linux host | Only what you mount | Can be cut | Most, some system calls missing | Untrusted code on Linux that is light on system calls |
| MicroVM | The hypervisor, with a guest kernel | Only what you copy or mount | Can be cut | Yes | Code nobody read, such as an agent’s |
For the analytics product, the script comes from a model and nobody reads it, so the last row is the one to use. The next section runs it.
Running agent-written Python in a VirtX microVM
VirtX is an open-source tool (Apache-2.0) that runs tasks in disposable Linux VMs from your own Python, Node or Rust code. Each sandbox is a microVM built on libkrun, a dynamic library providing virtualization-based process isolation capabilities, with its own Linux kernel on the hypervisor your machine already has:
- Linux: KVM
- macOS: Hypervisor.framework, on Apple silicon only
- Windows: the Windows Hypervisor Platform, on Windows 11 with an x86_64 processor
Install it with pip install virtx, with no Docker and no daemon to set up. Client.spawn() starts a VirtX server on your machine, and the sandbox boots from any OCI image, the image format Docker uses. The script below plays the product’s part.
It builds an image from python:3.12-slim with pandas, a library with compiled C code, and the sqlite3 command-line tool, so the packages download during the build and the run itself stays offline. It then copies in the user’s CSV and the model’s script, boots a sandbox with one CPU, 1 GiB of memory and no network, and runs the script with a 30 second limit. Two runaway jobs close it out, a list that grows until memory runs out and a loop that never ends, and for each one the script prints the exit code and the reason VirtX records:
import asyncio
from virtx import Client, Recipe
# The code a model wrote. Nobody has read it before it runs.AGENT_CODE = """import os, subprocess, urllib.requestimport pandas as pd
print("kernel:", os.uname().sysname, os.uname().release)
df = pd.read_csv("/work/orders.csv")print("median order:", df["amount"].median())
out = subprocess.run( ["sqlite3", ":memory:", ".mode csv", ".import /work/orders.csv orders", ".mode list", "SELECT region, SUM(amount) FROM orders GROUP BY region ORDER BY region;"], capture_output=True, text=True, check=True,)print("by region:", ", ".join(out.stdout.split()))
print("files in /work:", sorted(os.listdir("/work")))
try: urllib.request.urlopen("https://example.com", timeout=5) print("network: reached example.com")except Exception as e: print("network: blocked,", type(e).__name__)"""
# pandas ships compiled C code, and sqlite3 is a Linux command-line toolRECIPE = ( Recipe("python:3.12-slim") .run("pip install --no-cache-dir pandas") .run("apt-get update && apt-get install -y --no-install-recommends sqlite3"))
async def main() -> None: async with Client.spawn() as client: await client.build_image(RECIPE, "agent-python:1").complete()
# Its own kernel, one CPU, 1 GiB of memory and no way out sandbox = await client.create_sandbox( "agent-python:1", vcpus=1, memory_mib=1024, network=False ) try: await sandbox.create_dir_all("work") await sandbox.write_file( "work/orders.csv", "id,region,amount\n1,eu,40\n2,us,25\n3,eu,90\n" ) await sandbox.write_file("work/agent.py", AGENT_CODE) code = await sandbox.exec( ["python", "/work/agent.py"], timeout_ms=30_000 ).complete(print=True) print("exited", code)
# A list that grows until memory runs out mem = sandbox.exec( ["python", "-c", "a = []\nwhile True: a.append(bytearray(64 * 1024**2))"], timeout_ms=30_000, ) code = await mem.complete() ended = await (await mem).get() print("memory exited", code, ended.reason.value)
# A runaway loop is killed when its time runs out job = sandbox.exec(["python", "-c", "while True: pass"], timeout_ms=3_000) code = await job.complete() ended = await (await job).get() print("loop exited", code, ended.reason.value) finally: await sandbox.remove()
asyncio.run(main())We ran it with VirtX 0.2.1 on a Windows 11 laptop. It printed:
kernel: Linux 6.12.109median order: 40.0by region: eu|130, us|25files in /work: ['agent.py', 'orders.csv']network: blocked, URLErrorexited 0memory exited 137 oomloop exited 137 timeoutThe first two points show what kind of system the script ran on, and the last four map to the four groups:
- Its own kernel: the script reports a Linux kernel on a Windows host, so every system call it makes lands on the guest kernel inside the VM.
- A standard Linux system: pandas loaded its compiled C code and the script started sqlite3 as a subprocess, with no special build of either.
- Files: the script sees the image’s own files and the two that
write_fileput in /work, and nothing from your host unless you mount it. - Network:
network=Falseblocks outbound connections and name lookups, so the request failed withURLError. - Resources: the growing list was killed when the VM’s 1 GiB ran out, and the loop when its 3 seconds did. Both end with 137, the code a killed process gets, and VirtX records why: oom and timeout.
- Leftovers:
sandbox.remove()deletes everything the script wrote over the image.
The same code runs against a VirtX server on another machine of yours, or on VirtX cloud, which is in early access: only the Client.spawn() line changes. Setting up sandboxes lists every option create_sandbox takes.

What a sandbox still leaves for you to decide
A microVM keeps the script away from your machine, and it still runs whatever you hand it. Anything you copy in, mount or leave reachable becomes part of what the script can use, so the choices around the sandbox decide how safe the run is.

A few rules hold for every approach in this post:
- Keep secrets out. Do not pass API keys or tokens into the sandbox. Anything the script can read, it can print, and its output comes back to you.
- Mount the least you can. Copy in the one file the job needs, or mount a volume read-only, instead of sharing a folder.
- Leave the network off unless the job needs it. A script that must download packages can do it in a build step, with the run itself offline.
- Treat the output as untrusted too. A chart, a CSV or a printed answer from the script goes through the same checks as any user input before you show or store it.
In the analytics example, the product keeps its own database password and the model’s API key in its own process, and copies one CSV into each sandbox.
Choosing a Python sandbox for code nobody read
Python gives you no safe way to run untrusted code inside the interpreter that runs your product, and a venv was never meant to. WebAssembly, containers and gVisor each draw a real boundary, while a microVM gives agent-written code a kernel of its own, a standard Linux system for whatever packages and tools it reaches for, and a network you can switch off.
To try it, run the hello world, then swap in the script above with your own model’s code. For the case beyond Python, see running untrusted code in a microVM. Our practical guide to microVMs explains where they came from and when else they fit.
FAQs
Can you sandbox Python with exec() and a restricted globals dict?
No. The Python docs say overriding __builtins__ is not a security mechanism, since the code can still reach every builtin. Python’s introspection gives too many ways back to the modules you tried to remove.
Is a Python virtual environment a sandbox?
No. A venv gives a project its own set of packages, and the code in it still runs with your user’s files, environment variables and network access.
Is Pyodide safe for running untrusted Python?
Pyodide runs Python inside the WebAssembly sandbox of a browser or Node.js, which keeps the code away from the host’s files and system calls. Packages with native code need Pyodide builds, and subprocess and sockets do not work, so it fits a known, pure Python stack better than scripts an agent writes on the fly.
Do I need Linux to run Python in a microVM?
No. VirtX runs its microVMs on KVM on Linux, Hypervisor.framework on Apple silicon Macs and the Windows Hypervisor Platform on Windows 11 x86_64. The guest is always Linux, whatever the host is.
How do I stop sandboxed Python from reaching the internet?
Cut the sandbox’s network when you create it. In VirtX, network=False on create_sandbox blocks the guest’s outbound connections and name lookups, and ports you open still work.
