Use sandbox.kill() to terminate a sandbox and release its resources. Once killed, a sandbox cannot be recovered.
Basic Usage
from moru import Sandbox
sandbox = Sandbox.create()
# Do some work...
result = sandbox.commands.run("echo 'Hello'")
# Terminate the sandbox
sandbox.kill()
Kill by ID
You can also kill a sandbox without connecting to it first:
from moru import Sandbox
# Kill directly by ID
Sandbox.kill("sbx_abc123...")
Context Manager (Python)
Use Python’s context manager for automatic cleanup:
from moru import Sandbox
with Sandbox.create() as sandbox:
result = sandbox.commands.run("echo 'Hello'")
print(result.stdout)
# Sandbox is automatically killed when exiting the context
For async code:
import asyncio
from moru import AsyncSandbox
async def main():
async with await AsyncSandbox.create() as sandbox:
result = await sandbox.commands.run("echo 'Hello'")
print(result.stdout)
# Sandbox is automatically killed
asyncio.run(main())
Pause vs Kill (Beta)
Instead of killing, you can pause a sandbox to preserve its state:
from moru import Sandbox
sandbox = Sandbox.create()
# Write some files
sandbox.files.write("/data/important.txt", "Preserve this!")
# Pause instead of kill - filesystem is preserved
sandbox.beta_pause()
# Later, resume the sandbox
sandbox = Sandbox.connect("sbx_abc123...")
sandbox.connect() # Resume from paused state
# Data is still there
content = sandbox.files.read("/data/important.txt")
print(content) # Preserve this!
The pause feature is in beta. Paused sandboxes still count toward your quota and may have time limits.
Error Handling
from moru import Sandbox
from moru.exceptions import NotFoundException
try:
sandbox = Sandbox.connect("sbx_abc123...")
sandbox.kill()
except NotFoundException:
print("Sandbox already terminated")
Kill Multiple Sandboxes
Kill all sandboxes matching certain criteria:
from moru import Sandbox
# List and kill all running sandboxes
for info in Sandbox.list():
if info.metadata.get("environment") == "development":
Sandbox.kill(info.sandbox_id)
print(f"Killed {info.sandbox_id}")
What Happens on Kill
When a sandbox is killed:
- All running processes are terminated immediately
- The filesystem is deleted (unless paused)
- Network connections are closed
- Resources (CPU, memory, disk) are released
- The sandbox ID becomes invalid
Killing a sandbox is irreversible. All data in the sandbox filesystem is permanently deleted unless you’ve extracted it first.
Graceful Shutdown
For graceful cleanup, stop processes before killing:
from moru import Sandbox
sandbox = Sandbox.create()
# Start a background process
sandbox.commands.run("python3 server.py", background=True)
# Graceful shutdown
sandbox.commands.run("pkill -SIGTERM python3")
# Wait for cleanup
import time
time.sleep(2)
# Now kill
sandbox.kill()
Next Steps