#
Python SDK Reference
Complete reference documentation for the microsandbox Python SDK.
#
Installation
pip install microsandbox
#
Quick Start
import asyncio
from microsandbox import PythonSandbox
async def main():
async with PythonSandbox.create(name="my-sandbox") as sb:
exec = await sb.run("print('Hello, World!')")
print(await exec.output())
asyncio.run(main())
#
PythonSandbox
The main class for creating and managing Python execution environments.
PythonSandbox(
server_url: str = None,
namespace: str = "default",
name: str = None,
api_key: str = None
)
#
Class Methods
create()
Creates and automatically starts a new sandbox instance as an async context manager.
@classmethod
@asynccontextmanager
async def create(
cls,
server_url: str = None,
namespace: str = "default",
name: str = None,
api_key: str = None
)
Returns: An async context manager that yields a started PythonSandbox
instance
async with PythonSandbox.create(name="my-sandbox") as sb:
# Sandbox automatically started and stopped
exec = await sb.run("print('Hello!')")
print(await exec.output())
#
Instance Methods
start()
Starts the sandbox with optional resource constraints.
async def start(
self,
image: str = None,
memory: int = 512,
cpus: float = 1.0,
timeout: float = 180.0
) -> None
sandbox = PythonSandbox(name="resource-limited")
sandbox._session = aiohttp.ClientSession()
await sandbox.start(memory=1024, cpus=2.0)
stop()
Stops and cleans up the sandbox.
async def stop(self) -> None
run()
Executes Python code in the sandbox environment.
async def run(self, code: str) -> "Execution"
Returns: Execution
object with results
exec = await sb.run("print('Hello, World!')")
print(await exec.output())
code = """
import math
result = math.sqrt(16)
print(f"Square root of 16 is: {result}")
"""
exec = await sb.run(code)
#
Properties
command
Access to shell command execution interface.
@property
def command(self) -> "Command"
result = await sb.command.run("ls", ["-la", "/"])
print(await result.output())
metrics
Access to resource monitoring interface.
@property
def metrics(self) -> "Metrics"
cpu = await sb.metrics.cpu()
memory = await sb.metrics.memory()
print(f"CPU: {cpu}%, Memory: {memory} MiB")
is_started
Returns sandbox running status.
@property
def is_started(self) -> bool
name
Returns the sandbox identifier.
@property
def name(self) -> str
#
NodeSandbox
JavaScript/Node.js execution environment with identical API to PythonSandbox.
NodeSandbox(
server_url: str = None,
namespace: str = "default",
name: str = None,
api_key: str = None
)
All methods are identical to PythonSandbox
but execute JavaScript code.
from microsandbox import NodeSandbox
async with NodeSandbox.create(name="js-sandbox") as sb:
exec = await sb.run("console.log('Hello from Node.js!');")
print(await exec.output())
#
Execution
Represents the result of code execution from sandbox.run()
.
#
Methods
output()
Returns standard output from execution.
async def output(self) -> str
error()
Returns standard error from execution.
async def error(self) -> str
has_error()
Checks if execution produced errors.
def has_error(self) -> bool
#
Properties
status
Execution status.
@property
def status(self) -> str
language
Language used for execution.
@property
def language(self) -> str
Example: Handling Execution Results
exec = await sb.run("print('Hello'); import sys; sys.exit(1)")
print(f"Status: {exec.status}")
print(f"Language: {exec.language}")
print(f"Output: {await exec.output()}")
print(f"Has error: {exec.has_error()}")
#
CommandExecution
Represents the result of command execution from sandbox.command.run()
.
#
Methods
output()
Returns standard output from command execution.
async def output(self) -> str
error()
Returns standard error from command execution.
async def error(self) -> str
#
Properties
exit_code
Command exit code.
@property
def exit_code(self) -> int
success
True if command was successful (exit code 0).
@property
def success(self) -> bool
command
The command that was executed.
@property
def command(self) -> str
args
Arguments used for the command.
@property
def args(self) -> List[str]
#
Command
Interface for executing shell commands within sandboxes.
run()
Executes shell commands with arguments.
async def run(
self,
command: str,
args: List[str] = None,
timeout: int = None
) -> "CommandExecution"
Returns: CommandExecution
object with results
result = await sb.command.run("ls")
result = await sb.command.run("ls", ["-la", "/tmp"])
result = await sb.command.run("sleep", ["10"], timeout=5)
result = await sb.command.run("ls", ["/nonexistent"])
if result.success:
print("Output:", await result.output())
else:
print("Error:", await result.error())
print("Exit code:", result.exit_code)
#
Metrics
Interface for monitoring sandbox resource usage and performance.
#
Methods
cpu()
Current CPU usage percentage.
async def cpu(self) -> Optional[float]
memory()
Current memory usage in MiB.
async def memory(self) -> Optional[int]
disk()
Current disk usage in bytes.
async def disk(self) -> Optional[int]
is_running()
Sandbox running status.
async def is_running(self) -> bool
all()
All metrics as a dictionary.
async def all(self) -> Dict[str, Any]
Returns: Dictionary with keys: name
, namespace
, running
, cpu_usage
, memory_usage
, disk_usage
# Individual metrics
cpu = await sb.metrics.cpu()
memory = await sb.metrics.memory()
disk = await sb.metrics.disk()
running = await sb.metrics.is_running()
print(f"CPU: {cpu}%" if cpu is not None else "CPU: Not available")
print(f"Memory: {memory} MiB" if memory else "Memory: Not available")
print(f"Disk: {disk} bytes" if disk else "Disk: Not available")
print(f"Running: {running}")
# All metrics at once
metrics = await sb.metrics.all()
print(f"All metrics: {metrics}")
#
Usage Patterns
#
Context Manager (Recommended)
Automatic resource management with guaranteed cleanup.
async with PythonSandbox.create(name="my-sandbox") as sb:
exec = await sb.run("print('Hello, World!')")
print(await exec.output())
# Sandbox automatically stopped and cleaned up
#
Manual Lifecycle Management
Manual control over sandbox lifecycle.
import aiohttp
sandbox = PythonSandbox(name="my-sandbox")
sandbox._session = aiohttp.ClientSession()
try:
await sandbox.start(memory=1024, cpus=2.0)
exec = await sandbox.run("print('Hello, World!')")
print(await exec.output())
finally:
await sandbox.stop()
await sandbox._session.close()
#
State Persistence
Variables and imports persist between executions.
async with PythonSandbox.create(name="stateful") as sb:
await sb.run("x = 42")
await sb.run("y = x * 2")
exec = await sb.run("print(f'Result: {y}')")
print(await exec.output()) # Output: Result: 84
#
Error Handling
Comprehensive error handling patterns.
async with PythonSandbox.create(name="error-handling") as sb:
try:
exec = await sb.run("1/0") # Division by zero
if exec.has_error():
print("Error occurred:", await exec.error())
except RuntimeError as e:
print("Runtime error:", e)
#
File Operations
Creating and manipulating files within sandboxes.
async with PythonSandbox.create(name="files") as sb:
# Create a file using Python
await sb.run("""
with open('/tmp/test.txt', 'w') as f:
f.write('Hello from sandbox!')
""")
# Read the file using shell command
result = await sb.command.run("cat", ["/tmp/test.txt"])
print("File content:", await result.output())
#
Configuration
#
Environment Variables
#
Server Configuration
Default server URL: http://127.0.0.1:5555
#
Error Handling
Common Error Types
The SDK raises RuntimeError
for various conditions:
- Connection failures — Server unreachable or network issues
- Authentication errors — Invalid or missing API key
- Execution timeouts — Code/commands exceed time limits
- Invalid operations — Attempting operations on stopped sandboxes
#
Best Practices
try:
async with PythonSandbox.create(name="error-test") as sb:
exec = await sb.run("potentially_failing_code()")
if exec.has_error():
print("Execution error:", await exec.error())
else:
print("Success:", await exec.output())
except RuntimeError as e:
print(f"SDK error: {e}")
except Exception as e:
print(f"Unexpected error: {e}")
#
Best Practices
Recommended Practices
- Use context managers — Ensures automatic cleanup
- Set appropriate timeouts — Prevent hanging operations
- Handle errors gracefully — Use try-catch blocks
- Monitor resources — Use metrics interface
- Use meaningful names — Easier debugging and management
- Install packages once — Reuse sandbox for multiple executions
- Close HTTP sessions — When using manual lifecycle management
Common Pitfalls
- Forgetting to call
stop()
with manual lifecycle management - Not handling execution errors properly
- Setting timeouts too low for complex operations
- Creating too many concurrent sandboxes without resource limits