Endpoints and Web Servers
One-Off Functions
Running Arbitrary Images
Task Queues
Customizing Container Images
Autoscaling and Concurrency
Advanced Topics
Self-Hosting
Resources
Sandboxes
Process Management
Execute code and commands with real-time output streaming in your sandbox
The Sandbox provides process management through the process
property. You can execute Python code, run shell commands, and manage long-running processes with real-time output streaming.
Running Python Code
Basic Code Execution
Copy
Ask AI
from beam import Sandbox, Image
sandbox = Sandbox(image=Image(python_version=PythonVersion.Python311))
sb = sandbox.create()
# Run simple Python code
result = sb.process.run_code("print('Hello from sandbox!')")
print(result.result) # Hello from sandbox!
print(f"Exit code: {result.exit_code}") # 0
Complex Python Scripts
Copy
Ask AI
# Multi-line Python code
code = """
import numpy as np
import pandas as pd
# Generate sample data
data = np.random.randn(1000, 3)
df = pd.DataFrame(data, columns=['A', 'B', 'C'])
# Calculate statistics
stats = df.describe()
print("Data Statistics:")
print(stats)
# Save results
df.to_csv('/workspace/data.csv', index=False)
print("Data saved to /workspace/data.csv")
"""
response = sb.process.run_code(code)
print(response.result)
Error Handling
Copy
Ask AI
# Code with errors
response = sb.process.run_code("""
import nonexistent_module
print("This won't execute")
""")
print(f"Exit code: {response.exit_code}") # Non-zero exit code
print(f"Error output: {response.result}") # Error message
Executing Commands
Basic Command Execution
Copy
Ask AI
# Run a simple command
process = sb.process.exec("ls", "-la", "/workspace")
# Wait for completion
exit_code = process.wait()
print(f"Command completed with exit code: {exit_code}")
# Get all output
for line in process.logs:
print(line, end="")
Shell Commands
Copy
Ask AI
# Use shell features
process = sb.process.exec("echo $HOME && pwd && whoami")
# Wait and get output
process.wait()
for line in process.logs:
print(line, end="")
Working Directory
Copy
Ask AI
# Execute in specific directory
process = sb.process.exec("ls", "-la", cwd="/workspace")
process.wait()
# Create directory and work in it
sb.process.run_code("import os; os.makedirs('/workspace/myproject', exist_ok=True)")
process = sb.process.exec("touch", "test.txt", cwd="/workspace/myproject")
Environment Variables
Copy
Ask AI
# Set environment variables for command
env = {
"DATABASE_URL": "postgresql://localhost/mydb",
"DEBUG": "true",
"API_KEY": "secret-key"
}
process = sb.process.exec("env", "|", "grep", "DATABASE", env=env)
process.wait()
Non-blocking Execution
Background Processes
Copy
Ask AI
# Start a long-running process without waiting
process = sb.process.run_code("""
import time
for i in range(10):
print(f"Processing {i}...")
time.sleep(1)
""", blocking=False)
print(f"Process started with PID: {process.pid}")
# Do other work while it runs
print("Process is running in background...")
# Check if still running
print(f"Exit code: {process.exit_code}") # -1 if still running
# Wait for completion when ready
process.wait()
print("Process completed!")
Real-time Output Streaming
Copy
Ask AI
# Start process and stream output in real-time
process = sb.process.run_code("""
import time
for i in range(5):
print(f"Step {i}: Processing...")
time.sleep(1)
print("Done!")
""", blocking=False)
# Stream output as it happens
for line in process.logs:
print(f"[REAL-TIME] {line}", end="")
Process Control
Process Management
Copy
Ask AI
# Start multiple processes
process1 = sb.process.exec("sleep", "30", blocking=False)
process2 = sb.process.exec("sleep", "60", blocking=False)
print(f"Process 1 PID: {process1.pid}")
print(f"Process 2 PID: {process2.pid}")
# List all running processes
for p in sb.process.list_processes():
print(f"PID {p.pid}: {p.status()}")
# Kill specific process
process1.kill()
print("Process 1 killed")
# Get process by PID
specific_process = sb.process.get_process(process2.pid)
print(f"Process 2 status: {specific_process.status()}")
Process Status and Monitoring
Copy
Ask AI
# Start a process
process = sb.process.exec("sleep", "10", blocking=False)
# Monitor status
while True:
exit_code, status = process.status()
print(f"PID {process.pid}: Exit code {exit_code}, Status: {status}")
if exit_code >= 0:
print("Process completed")
break
time.sleep(1)
Process Output Streams
Copy
Ask AI
# Start process with output
process = sb.process.run_code("""
import sys
print("This goes to stdout")
print("This also goes to stdout", file=sys.stdout)
print("This goes to stderr", file=sys.stderr)
""", blocking=False)
# Read stdout
print("=== STDOUT ===")
for line in process.stdout:
print(f"STDOUT: {line}", end="")
# Read stderr
print("=== STDERR ===")
for line in process.stderr:
print(f"STDERR: {line}", end="")
# Read combined logs
print("=== COMBINED LOGS ===")
for line in process.logs:
print(f"LOG: {line}", end="")
Was this page helpful?
On this page
- Running Python Code
- Basic Code Execution
- Complex Python Scripts
- Error Handling
- Executing Commands
- Basic Command Execution
- Shell Commands
- Working Directory
- Environment Variables
- Non-blocking Execution
- Background Processes
- Real-time Output Streaming
- Process Control
- Process Management
- Process Status and Monitoring
- Process Output Streams
Assistant
Responses are generated using AI and may contain mistakes.