Code Execution
Execute code on InstaVM sandboxes using execute() for synchronous runs and execute_async() for long-running operations.
execute(command)
Run code synchronously and return the result:
from instavm import InstaVM
with InstaVM('your_api_key') as vm:
result = vm.execute("print(2 + 2)")
print(result['output']) # "4\n"
print(result['execution_time']) # 0.05
Multi-line code
result = vm.execute("""
import math
result = math.sqrt(16)
print(f"Square root of 16 is {result}")
""")
Installing packages
Packages installed in one execute() call persist for subsequent calls in the same session:
with InstaVM('your_api_key') as vm:
vm.execute("import subprocess; subprocess.check_call(['pip', 'install', 'pandas'])")
result = vm.execute("import pandas as pd; print(pd.__version__)")
print(result['output'])
execute_async(command, language=None, timeout=None)
Start a long-running execution without blocking:
with InstaVM('your_api_key') as vm:
result = vm.execute_async("""
import time
for i in range(10):
print(f"Step {i}")
time.sleep(1)
""")
execution_id = result.get('execution_id')
print(f"Started: {execution_id}")
Use execute_async() when your code takes more than a few seconds and you want to check status later or run other operations in parallel.
execute_streaming(command) [Deprecated]
This method is deprecated. The API no longer supports streaming execution. Use execute() or execute_async() instead.
Return value
Both execute() and execute_async() return a dictionary:
| Field | Type | Description |
|---|---|---|
output | str | stdout from the execution |
execution_time | float | Time in seconds |
execution_id | str | Unique ID for this execution (async only) |
success | bool | Whether the execution completed without error |
Next steps
- Session Management -- how sessions persist state between executions
- Error Handling -- handling execution errors