Skip to content

Python Preset

Convenience helpers for running Python code in machinees.

TypeScript: PythonMachine Class

The PythonMachine class provides Python-specific methods.

typescript
import { PythonMachine } from 'smolvm';

const machine = await PythonMachine.create({ name: 'python-env' });

try {
  // Run Python code directly
  const result = await machine.runCode(`
import sys
print(f"Python {sys.version}")
print(2 ** 10)
  `);
  console.log(result.stdout);

  // Check Python version
  const version = await machine.version();
  console.log(version);  // "3.12.x"

  // Install packages
  await machine.pip(['requests', 'pandas']);

  // List installed packages
  const packages = await machine.listPackages();
  console.log(packages);

  // Run with setup code
  const calcResult = await machine.runWithSetup(
    'import math',
    'print(math.pi)'
  );
  console.log(calcResult.stdout);  // "3.14159..."

  // Run a file from mounted directory
  const fileResult = await machine.runFile('/workspace/script.py');
} finally {
  await machine.stop();
  await machine.delete();
}

Methods

MethodDescription
runCode(code)Execute Python code string
runFile(path)Execute a Python file
pip(packages)Install packages with pip
version()Get Python version
listPackages()List installed packages
runWithSetup(setup, code)Run with setup code

Python: Preset Functions

Python SDK provides simple functions for common tasks.

python
from smolvm.presets import python_machine, python_file

# Execute Python code directly
result = await python_machine("""
import sys
print(f"Python {sys.version}")

# Do computation
data = [1, 2, 3, 4, 5]
print(f"Sum: {sum(data)}")
""")
print(result.stdout)

# Execute a Python file
result = await python_file("/path/to/script.py")
print(result.stdout)

# With custom configuration
from smolvm import MachineConfig, ResourceSpec

result = await python_machine(
    """
import numpy as np
arr = np.array([1, 2, 3])
print(arr * 2)
    """,
    config=MachineConfig(
        name="numpy-machine",
        resources=ResourceSpec(memory_mb=1024)
    )
)

Functions

FunctionDescription
python_machine(code, config?)Execute Python code
python_file(path, config?)Execute Python file

Using Packages

Installing Packages (TypeScript)

typescript
const machine = await PythonMachine.create({ name: 'with-packages' });

// Install multiple packages
await machine.pip(['requests', 'beautifulsoup4', 'lxml']);

// Use them
const result = await machine.runCode(`
import requests
from bs4 import BeautifulSoup

r = requests.get("https://example.com")
soup = BeautifulSoup(r.text, "lxml")
print(soup.title.string)
`);

Pre-installed Packages

The python:3.12-alpine image includes:

  • Standard library
  • pip

For additional packages, install them at runtime or use a custom image.

Custom Python Image

For reproducible environments, use a custom image:

typescript
// Create machine with custom image
const machine = await Machine.create({
  name: 'custom-python',
});

// Run with your custom image
const result = await machine.run(
  'myregistry/python-ml:latest',
  ['python', '-c', 'import torch; print(torch.__version__)']
);

Data Science Example

typescript
const machine = await PythonMachine.create({
  name: 'data-science',
  resources: { cpus: 2, memoryMb: 2048 },
  mounts: [{ source: '/data', target: '/data' }]
});

await machine.pip(['pandas', 'matplotlib']);

const result = await machine.runCode(`
import pandas as pd
import matplotlib.pyplot as plt

# Read data
df = pd.read_csv('/data/sales.csv')

# Analyze
summary = df.groupby('region')['revenue'].sum()
print(summary)

# Plot (saves to file)
summary.plot(kind='bar')
plt.savefig('/data/chart.png')
print("Chart saved to /data/chart.png")
`);

console.log(result.stdout);