Sessions
Sessions represent a persistent connection to a sandbox. All code executions within a session share the same VM, filesystem, and process state.
How sessions work
When you create an InstaVM client and call execute(), a session is automatically created. Subsequent calls to execute() on the same client reuse the same session, which means:
- Variables, files, and installed packages persist between calls
- Each call runs in the same VM
- The session ends when you call
kill(), exit a context manager, or the lifetime expires
from instavm import InstaVM
with InstaVM('your_api_key') as vm:
vm.execute("x = 42")
result = vm.execute("print(x)") # Output: 42
# Same VM, same state
Session lifecycle
create session → VM boots (~200ms) → execute code → ... → terminate
- Created -- Session allocated, VM provisioning begins.
- Active -- VM is running. You can execute code, upload/download files, and manage egress.
- Terminated -- Session closed. VM and all its state are destroyed.
Automatic session management
Use a context manager to guarantee cleanup:
with InstaVM('your_api_key') as vm:
vm.execute("print('hello')")
# VM is killed automatically here
Manual session management
If you need more control:
vm = InstaVM('your_api_key')
try:
result = vm.execute("print('hello')")
# Check session status
if vm.is_session_active():
info = vm.get_session_info()
print(f"Session ID: {info['session_id']}")
finally:
vm.close_session()
Session expiry
Sessions have a configurable lifetime. When the lifetime expires, the VM is terminated and all state is lost. Set the lifetime when creating a VM directly:
client = InstaVM('your_api_key')
vm = client.vms.create(
vm_lifetime_seconds=3600, # 1 hour
wait=True
)
Multi-execute pattern
Sessions are designed for multi-step workflows. Install dependencies once, then run multiple scripts:
with InstaVM('your_api_key') as vm:
# Step 1: Install dependencies
vm.execute("import subprocess; subprocess.check_call(['pip', 'install', 'pandas'])")
# Step 2: Load data
vm.execute("import pandas as pd; df = pd.DataFrame({'a': [1,2,3]})")
# Step 3: Process
result = vm.execute("print(df.describe())")
print(result['output'])