Skip to main content

Python SDK

The InstaVM Python SDK provides a simple and intuitive way to interact with the InstaVM API. It handles session management, error handling, and provides both synchronous and streaming execution capabilities.

Installation

pip install instavm

Quick Start

from instavm import InstaVM

# Initialize with your API key
vm = InstaVM('your_api_key_here')

# Execute code
result = vm.execute("print('Hello from InstaVM!')")
print(result)

Client Configuration

Basic Configuration

from instavm import InstaVM

# Default configuration
client = InstaVM('your_api_key')

# Custom configuration
client = InstaVM(
api_key='your_api_key',
base_url='https://api.instavm.io', # Custom API endpoint
timeout=30, # Request timeout in seconds
max_retries=3 # Number of retry attempts
)

Using Environment Variables

import os
from instavm import InstaVM

# Set API key via environment variable
os.environ['INSTAVM_API_KEY'] = 'your_api_key'
client = InstaVM(os.getenv('INSTAVM_API_KEY'))

Core Methods

execute(command)

Execute code synchronously on a virtual machine.

from instavm import InstaVM

with InstaVM('your_api_key') as vm:
result = vm.execute("""
import math
result = math.sqrt(16)
print(f"Square root of 16 is {result}")
""")

print(result['output']) # Square root of 16 is 4.0
print(result['execution_time']) # 0.123

execute_streaming(command, on_output=None)

Execute code with real-time streaming output.

from instavm import InstaVM

def handle_output(output):
print(f"Real-time: {output}")

with InstaVM('your_api_key') as vm:
# Stream output in real-time
for output in vm.execute_streaming("pip install requests", on_output=handle_output):
# Process each line as it comes
pass

upload_file(file_path)

Upload a file to the virtual machine.

from instavm import InstaVM

with InstaVM('your_api_key') as vm:
# Upload a file
result = vm.upload_file('/path/to/local/file.txt')
print(f"Uploaded {result['filename']}, size: {result['size']} bytes")

# Now execute code that uses the file
vm.execute("with open('file.txt', 'r') as f: print(f.read())")

get_usage()

Get usage metrics for the current session.

from instavm import InstaVM

with InstaVM('your_api_key') as vm:
vm.execute("print('Hello World')")

usage = vm.get_usage()
print(f"CPU Time: {usage['cpu_time']}s")
print(f"Memory Used: {usage['memory_used']} bytes")
print(f"Network I/O: {usage['network_io']} bytes")

Session Management

from instavm import InstaVM

# Context manager automatically handles session lifecycle
with InstaVM('your_api_key') as vm:
result = vm.execute("print('Session managed automatically')")
# Session automatically closed when exiting context

Manual Session Management

from instavm import InstaVM

vm = InstaVM('your_api_key')
try:
# Session started automatically
result = vm.execute("print('Manual session management')")

# Check session status
if vm.is_session_active():
print("Session is active")

# Get session info
info = vm.get_session_info()
print(f"Session ID: {info['session_id']}")

finally:
# Always close session
vm.close_session()

Error Handling

The SDK provides specific exception types for different error scenarios:

from instavm import (
InstaVM,
AuthenticationError,
SessionError,
ExecutionError,
NetworkError,
RateLimitError
)

try:
vm = InstaVM('invalid_api_key')
result = vm.execute("print('This will fail')")

except AuthenticationError:
print("Invalid API key provided")

except SessionError as e:
print(f"Session error: {e}")

except ExecutionError as e:
print(f"Code execution failed: {e}")

except NetworkError as e:
print(f"Network issue: {e}")

except RateLimitError as e:
print(f"Rate limit exceeded: {e}")

except Exception as e:
print(f"Unexpected error: {e}")

Advanced Examples

Data Visualization with Matplotlib

from instavm import InstaVM
import base64

with InstaVM('your_api_key') as vm:
result = vm.execute("""
import subprocess
import sys
import base64

# Install matplotlib
subprocess.check_call([sys.executable, "-m", "pip", "install", "matplotlib"])

import matplotlib.pyplot as plt
import numpy as np

# Generate data
x = np.linspace(0, 10, 100)
y = np.sin(x)

# Create plot
plt.figure(figsize=(10, 6))
plt.plot(x, y, 'b-', linewidth=2, label='sin(x)')
plt.xlabel('x')
plt.ylabel('y')
plt.title('Sine Wave Generated on InstaVM')
plt.legend()
plt.grid(True, alpha=0.3)

# Save to bytes and encode
import io
buf = io.BytesIO()
plt.savefig(buf, format='png', dpi=150, bbox_inches='tight')
buf.seek(0)

# Return base64 encoded image
image_base64 = base64.b64encode(buf.read()).decode('utf-8')
print(f"IMAGE_DATA:{image_base64}")
""")

# Extract image data from output
if "IMAGE_DATA:" in result['output']:
image_data = result['output'].split("IMAGE_DATA:")[1].strip()
# Save locally or display
with open('sine_wave.png', 'wb') as f:
f.write(base64.b64decode(image_data))
print("Visualization saved as sine_wave.png")

File Processing with FFmpeg

from instavm import InstaVM

with InstaVM('your_api_key') as vm:
# Upload video file
upload_result = vm.upload_file('/path/to/input_video.mp4')

# Process with FFmpeg
result = vm.execute("""
import subprocess

# Install FFmpeg
subprocess.run(['apt-get', 'update'], check=True)
subprocess.run(['apt-get', 'install', '-y', 'ffmpeg'], check=True)

# Convert video
subprocess.run([
'ffmpeg', '-i', 'input_video.mp4',
'-vf', 'scale=640:480',
'-codec:v', 'libx264',
'-codec:a', 'aac',
'output_video.mp4'
], check=True)

print("Video processing completed")
""")

# Download processed file (implementation depends on your setup)
print("Video processed successfully!")

Package Installation and Usage

from instavm import InstaVM

with InstaVM('your_api_key') as vm:
# Install and use scientific packages
result = vm.execute("""
import subprocess
import sys

# Install scientific packages
packages = ['numpy', 'pandas', 'scikit-learn']
for package in packages:
subprocess.check_call([sys.executable, "-m", "pip", "install", package])

# Use the packages
import numpy as np
import pandas as pd
from sklearn.linear_model import LinearRegression

# Generate sample data
X = np.random.rand(100, 1) * 10
y = 2.5 * X.ravel() + np.random.randn(100) * 2

# Fit model
model = LinearRegression()
model.fit(X, y)

print(f"Model coefficient: {model.coef_[0]:.2f}")
print(f"Model intercept: {model.intercept_:.2f}")
print(f"Model score: {model.score(X, y):.3f}")
""")

print(result['output'])

Performance Tips

  1. Reuse sessions: Keep sessions alive for multiple operations to avoid startup overhead
  2. Use streaming for long operations: Monitor progress with execute_streaming()
  3. Handle errors gracefully: Implement proper retry logic for network issues
  4. Close sessions: Always close sessions to free up resources

Configuration Options

ParameterDefaultDescription
api_keyRequiredYour InstaVM API key
base_urlhttps://api.instavm.ioAPI endpoint URL
timeout30Request timeout in seconds
max_retries3Number of retry attempts for failed requests

Next Steps