Skip to main content

ScaleBox Python SDK - A multi-language code execution sandbox with Python, R, Node.js, Deno/TypeScript, Java, and Bash support

Project description

Scalebox Python SDK

CI/CD Pipeline Python Version License: MIT PyPI Version Downloads Code Style: Black Type Check: MyPy Linting: Flake8 Import Sorting: isort Multi-Language Support

中文文档

A Python SDK for executing multi-language code in a controlled sandbox environment, supporting both synchronous and asynchronous modes, along with multi-language kernels (Python, R, Node.js, Deno/TypeScript, Java/IJAVA, Bash). Comprehensive real-world test cases and scripts are provided.

Features

  • Multi-language kernels: Python, R, Node.js, Deno/TypeScript, Java/IJAVA, Bash
  • Execution modes: Synchronous Sandbox and asynchronous AsyncSandbox
  • Persistent context: Retain variables/state across multiple executions
  • Callback subscriptions: stdout, stderr, results, and errors
  • Rich result formats: text, html, markdown, svg, png, jpeg, pdf, latex, json, javascript, chart, data, and more
  • Real-world testing: Comprehensive test coverage for sync/async and multi-language examples

Requirements

  • Python 3.12+
  • Accessible Scalebox environment or local service

Installation

# Clone the repository
git clone https://github.com/scalebox-dev/scalebox-sdk-python.git
cd scalebox-sdk-python

# Recommended: use a virtual environment
python3 -m venv venv
source venv/bin/activate

# Install dependencies
pip install -r scalebox/requirements.txt

If you're using the package directly from source (not via pip), add the scalebox directory to your Python path or copy it to your venv's site-packages:

cp -r scalebox venv/lib/python3.12/site-packages/

Configuration

Credentials can be read from environment variables or a .env file:

  • SBX_API_KEY

Example:

# .env
SBX_API_KEY=***

Or:

export SBX_API_KEY=***

Optional: Use python-dotenv to automatically load .env:

pip install python-dotenv

Quick Start (Synchronous)

from dotenv import load_dotenv; load_dotenv()
from scalebox.code_interpreter import Sandbox

sandbox = Sandbox.create()  # Default lifetime: 5 minutes
execution = sandbox.run_code("print('hello world')", language="python")
print(execution.logs.stdout)

files = sandbox.files.list("/")
print(files)

Quick Start (Asynchronous)

import asyncio
from dotenv import load_dotenv; load_dotenv()
from scalebox.code_interpreter import AsyncSandbox

async def main():
    sandbox = await AsyncSandbox.create()
    exec_ = await sandbox.run_code("print('async hello')", language="python")
    print(exec_.logs.stdout)

asyncio.run(main())

Multi-Language Examples

  • Python: language="python"
  • R: language="r"
  • Node.js: language="nodejs"
  • Deno/TypeScript: language="typescript"
  • Java (IJAVA/pure Java): language="ijava" or language="java"
  • Bash: language="bash"

Node.js Example:

from scalebox.code_interpreter import Sandbox
sbx = Sandbox.create()
code = """
console.log("Hello from Node.js!");
const x = 1 + 2; console.log(`x=${x}`);
"""
result = sbx.run_code(code, language="nodejs")
print(result.logs.stdout)

R Example:

from scalebox.code_interpreter import Sandbox
sbx = Sandbox.create()
code = """
print("Hello from R!")
x <- mean(c(1,2,3,4,5))
print(paste("mean:", x))
"""
res = sbx.run_code(code, language="r")
print(res.logs.stdout)

Deno/TypeScript Example:

from scalebox.code_interpreter import Sandbox
sbx = Sandbox.create()
ts = """
console.log("Hello from Deno/TypeScript!")
const nums: number[] = [1,2,3]
console.log(nums.reduce((a,b)=>a+b, 0))
"""
res = sbx.run_code(ts, language="typescript")
print(res.logs.stdout)

Java/IJAVA Example:

from scalebox.code_interpreter import Sandbox
sbx = Sandbox.create()
code = """
System.out.println("Hello from IJAVA!");
int a = 10, b = 20; System.out.println(a + b);
"""
res = sbx.run_code(code, language="java")
print(res.logs.stdout)

Bash Example:

from scalebox.code_interpreter import Sandbox
sbx = Sandbox.create()
res = sbx.run_code("echo 'Hello from Bash'", language="bash")
print(res.logs.stdout)

Context Management

Context allows you to reuse variables/state across multiple executions:

from scalebox.code_interpreter import Sandbox
sbx = Sandbox.create()
ctx = sbx.create_code_context(language="python", cwd="/tmp")

sbx.run_code("counter = 0", context=ctx)
sbx.run_code("counter += 1; print(counter)", context=ctx)
# Must clean up when done
sbx.destroy_context(ctx)

Async API:

from scalebox.code_interpreter import AsyncSandbox

async def demo():
    sbx = await AsyncSandbox.create()
    ctx = await sbx.create_code_context(language="python", cwd="/tmp")
    await sbx.run_code("counter = 0", context=ctx)
    await sbx.run_code("counter += 1; print(counter)", context=ctx)
    await sbx.destroy_context(ctx)

Callbacks (Optional)

from scalebox.code_interpreter import Sandbox
from scalebox.code_interpreter import OutputMessage, Result, ExecutionError

sbx = Sandbox.create()

def on_stdout(msg: OutputMessage):
    print("STDOUT:", msg.content)

def on_stderr(msg: OutputMessage):
    print("STDERR:", msg.content)

def on_result(res: Result):
    print("RESULT formats:", list(res.formats()))

def on_error(err: ExecutionError):
    print("ERROR:", err.name, err.value)

sbx.run_code(
    "print('with callbacks')",
    language="python",
    on_stdout=on_stdout,
    on_stderr=on_stderr,
    on_result=on_result,
    on_error=on_error,
)

Result Formats

Result may contain the following data fields:

  • text, html, markdown, svg, png, jpeg, pdf, latex
  • json_data, javascript, data, chart
  • execution_count, is_main_result, extra

Use list(result.formats()) to view available formats.

Running Tests

The test/ directory contains comprehensive real-world use cases (not unittest-style, direct script-style), covering:

  • Synchronous and asynchronous comprehensive test cases
  • Multi-language kernels (Python, R, Node.js, Deno/TypeScript, Java/IJAVA, Bash)
  • Context management, callbacks, and result formats

Run syntax checks:

cd test
python3 -m py_compile test_code_interpreter_sync_comprehensive.py
python3 -m py_compile test_code_interpreter_async_comprehensive.py

It's recommended to prepare dependencies in a virtual environment and install language runtimes (such as R, Node, Deno, JDK/IJAVA, etc.) as needed, ensuring each kernel can be executed by the backend.

Version Management

This project uses automated version management with support for Semantic Versioning.

🚀 Automatic Version Bumping

Use the built-in script to bump versions:

# Bump patch version (0.1.1 -> 0.1.2)
python scripts/bump_version.py patch

# Bump minor version (0.1.1 -> 0.2.0)
python scripts/bump_version.py minor

# Bump major version (0.1.1 -> 1.0.0)
python scripts/bump_version.py major

📦 Automated Release Process

🚀 Method 1: GitHub Actions One-Click Bump (Recommended)

  1. Navigate to GitHub Actions page
  2. Select "CI/CD Pipeline" workflow
  3. Click "Run workflow" button
  4. Select version type:
    • patch: Patch version (0.1.1 → 0.1.2)
    • minor: Minor version (0.1.1 → 0.2.0)
    • major: Major version (0.1.1 → 1.0.0)
  5. Select auto-commit option
  6. Click run - The system will automatically complete all steps!

🔧 Method 2: Local Script Bump

  1. Version Bump: Use bump_version.py script
  2. GitHub Actions: Automatically build and publish to PyPI
  3. Trigger Conditions:
    • Push to main branch
    • Create v* tag (e.g., v0.1.2)

🔧 Version File Synchronization

The script automatically updates versions in the following files:

  • scalebox/__init__.py
  • scalebox/version.py
  • pyproject.toml
  • CHANGELOG.md (optional)

📋 Release Steps

# 1. Bump version
python scripts/bump_version.py patch

# 2. Check changes
git diff

# 3. Commit changes
git add .
git commit -m "Bump version to 0.1.2"

# 4. Push and create tag
git push origin main
git push origin --tags

# 5. GitHub Actions will automatically publish to PyPI

🏷️ Version Rules

  • MAJOR: Incompatible API changes
  • MINOR: Backward-compatible feature additions
  • PATCH: Backward-compatible bug fixes

Troubleshooting

  • Import/dependency errors: Ensure venv is activated and all required dependencies from scalebox/requirements.txt are installed
  • ModuleNotFoundError: Add the project root path to sys.path in test scripts, or run from the project root directory
  • External kernels unavailable: Ensure the environment has the corresponding language runtime installed (R/Node/Deno/JDK) and the backend has enabled that kernel
  • Timeout/network issues: Check network connectivity and backend service accessibility, increase timeout/request_timeout if necessary

License

This project is licensed under the terms of the LICENSE file in the repository.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

scalebox_sdk-1.0.1.tar.gz (245.4 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

scalebox_sdk-1.0.1-py3-none-any.whl (326.4 kB view details)

Uploaded Python 3

File details

Details for the file scalebox_sdk-1.0.1.tar.gz.

File metadata

  • Download URL: scalebox_sdk-1.0.1.tar.gz
  • Upload date:
  • Size: 245.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for scalebox_sdk-1.0.1.tar.gz
Algorithm Hash digest
SHA256 a8e042daea345bf1c406296ab1dd2d19f8c12bb976100a330facc445dead24db
MD5 3e3e28544c0b653516edfd1e38e89310
BLAKE2b-256 00c015cb104c26fcac6c6b000b0ee33a0213caaccbd987415379cb00f243543e

See more details on using hashes here.

File details

Details for the file scalebox_sdk-1.0.1-py3-none-any.whl.

File metadata

  • Download URL: scalebox_sdk-1.0.1-py3-none-any.whl
  • Upload date:
  • Size: 326.4 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for scalebox_sdk-1.0.1-py3-none-any.whl
Algorithm Hash digest
SHA256 b4ecf74978b9d1dde97601ecb4fa95ac3a47158589121df32a5536e6198ad3ec
MD5 ea9af57ebbdf28052d0e236e02b8bfbd
BLAKE2b-256 2ef1820d5a47641f6865b87d71bc0c3c2daee0548d6e890f1dad3b1ef4aed3e0

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page