Skip to main content
CodeBox is BoxLite’s purpose-built sandbox for running untrusted Python code. It auto-installs missing packages, captures output, and keeps your host system completely safe. This tutorial walks through the core workflow.

What you’ll build

A script that:
  1. Creates an isolated CodeBox
  2. Runs untrusted Python code inside it
  3. Auto-installs required packages
  4. Returns the output to your application

Prerequisites

Requires Python 3.10+.

Step 1: Run simple code

Start with a basic example — execute a Python snippet and print the result.
run_code.py
What’s happening:
  • CodeBox creates a lightweight VM with a Python runtime pre-installed
  • Your code runs inside the VM — completely isolated from the host
  • Output is captured and returned as a string
  • The VM is cleaned up automatically when the context exits

Step 2: Auto-install packages

CodeBox detects missing imports and installs them automatically. No manual pip install needed.
auto_install.py

Step 3: Install packages explicitly

When you need specific versions or want to pre-install packages before running code, use install_package().
explicit_install.py
For data-heavy workloads (pandas, numpy, matplotlib), increase memory to 4096 MiB or more. The default 2048 MiB is enough for most code execution.

Step 4: Run a script file

Use run_script() to execute a Python script from your host filesystem inside the box.
run_script() reads the script from your host machine and executes it inside the box. It does not look for files already inside the guest.
analysis.py
run_script.py

Step 5: Run multiple snippets in the same box

A single CodeBox can run many snippets sequentially. Filesystem state persists between calls — installed packages and written files remain available. However, in-memory state (variables, functions) does not persist.
Each run() call spawns a separate Python process. Variables and functions defined in one run() call are not available in the next. Use the filesystem to share data between calls.
multi_run.py

What’s next?

Upload & download files

Move files in and out of your sandbox to process data and retrieve results.

Connect to an LLM

Wire up OpenAI function calling so an LLM can execute code in your sandbox.

CodeBox API reference

Full API docs for run(), run_script(), install_package(), and more.

AI agent integration

Advanced patterns: concurrency, timeouts, security presets, and production configuration.