> ## Documentation Index
> Fetch the complete documentation index at: https://docs.hopx.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Supported Languages

> Programming languages supported by HopX sandboxes and their specific features. Learn about Python, JavaScript, Bash, Go, and other languages available in HopX sandbox environments.

HopX sandboxes support multiple programming languages for code execution. Each language has specific features, pre-installed packages, and capabilities.

## Overview

HopX currently supports the following languages:

* **Python** - Full-featured Python environment with data science libraries
* **JavaScript/Node.js** - Modern JavaScript runtime with npm support
* **Bash** - Shell scripting and command execution
* **Go** - Go programming language runtime

<Note>
  Language support depends on the template you use. The `code-interpreter` template includes Python, JavaScript, and Bash. Other templates may support different language combinations.
</Note>

## Python

Python is the most feature-rich language in HopX sandboxes, with extensive pre-installed packages for data science, web development, and automation.

### Version

* **Python 3.11+** (varies by template)

### Pre-installed Packages

Common packages available in most Python templates:

* **Data Science**: `pandas`, `numpy`, `matplotlib`, `scipy`, `scikit-learn`
* **Web**: `requests`, `httpx`, `flask`, `fastapi`
* **Utilities**: `beautifulsoup4`, `ipykernel`, `jupyter-client`
* **System**: `git`, `curl`, `wget`, `vim`, `nano`

### Features

* ✅ **Rich Output Capture**: Automatically captures matplotlib plots, pandas DataFrames, and other visualizations
* ✅ **IPython Kernel**: Interactive Python execution with Jupyter kernel support
* ✅ **Package Installation**: Install additional packages with `pip`
* ✅ **File Operations**: Full filesystem access for reading/writing files
* ✅ **Environment Variables**: Access via `os.getenv()` or `os.environ`

### Example

```python theme={null}
from hopx_ai import Sandbox
from hopx_ai.exceptions import APIError, ResourceLimitError

try:
    sandbox = Sandbox.create(template="code-interpreter")
    
    # Execute Python code
    result = sandbox.run_code("""
    import pandas as pd
    import matplotlib.pyplot as plt
    
    data = {'x': [1, 2, 3, 4], 'y': [1, 4, 9, 16]}
    df = pd.DataFrame(data)
    print(df.describe())
    
    plt.plot(df['x'], df['y'])
    plt.savefig('/tmp/plot.png')
    """, language="python")
    
    print(result.stdout)
    # Rich outputs (plots, DataFrames) are automatically captured
    
    sandbox.kill()
except APIError as e:
    print(f"API error: {e}")
except ResourceLimitError as e:
    print(f"Resource limit exceeded: {e}")
except Exception as e:
    print(f"Unexpected error: {e}")
```

**Expected Output:**

```
                x          y
count   4.000000   4.000000
mean    2.500000   7.500000
std     1.290994   6.454972
min     1.000000   1.000000
25%     1.750000   3.250000
50%     2.500000   6.500000
75%     3.250000  11.750000
max     4.000000  16.000000
```

Rich outputs (plots, DataFrames) are automatically captured in `result.rich_outputs`.

## JavaScript/Node.js

JavaScript execution runs in a Node.js environment with access to npm packages and modern JavaScript features.

### Version

* **Node.js 18+** (varies by template)

### Pre-installed Packages

* **Runtime**: Node.js with npm
* **Kernel**: iJavaScript kernel for interactive execution
* **System Tools**: Standard Unix utilities

### Features

* ✅ **npm Support**: Install packages with `npm install`
* ✅ **ES Modules**: Support for modern ES6+ syntax
* ✅ **Rich Output**: Can generate HTML, JSON, and text outputs
* ✅ **Async/Await**: Full support for asynchronous operations
* ✅ **File System**: Access to Node.js `fs` module

### Example

```javascript theme={null}
import { Sandbox } from '@hopx-ai/sdk';
import { APIError, ResourceLimitError } from '@hopx-ai/sdk';

try {
  const sandbox = await Sandbox.create({ template: 'code-interpreter' });
  
  // Execute JavaScript code
  const result = await sandbox.runCode(`
  const fs = require('fs');
  const data = { message: 'Hello from Node.js!', timestamp: Date.now() };
  console.log(JSON.stringify(data, null, 2));
  
  // Write to file
  fs.writeFileSync('/tmp/output.json', JSON.stringify(data));
  `, { language: 'javascript' });
  
  console.log(result.stdout);
  
  await sandbox.kill();
} catch (error) {
  if (error instanceof APIError) {
    console.error(`API error: ${error.message}`);
  } else if (error instanceof ResourceLimitError) {
    console.error(`Resource limit exceeded: ${error.message}`);
  } else {
    console.error(`Unexpected error: ${error.message}`);
  }
}
```

**Expected Output:**

```json theme={null}
{
  "message": "Hello from Node.js!",
  "timestamp": 1706284800000
}
```

### JavaScript-Specific Features

The JavaScript SDK includes some unique features:

* **IPython Kernel Support**: `sandbox.runIpython()` method for interactive JavaScript execution
* **TypeScript Types**: Full TypeScript support with type definitions
* **Async Generators**: WebSocket streaming uses async generators (`for await...of`)

## Bash

Bash provides shell scripting capabilities for system administration, automation, and command execution.

### Features

* ✅ **Shell Commands**: Execute any shell command or script
* ✅ **Pipelines**: Support for command pipelines and redirection
* ✅ **Environment Variables**: Access via `$VARIABLE_NAME` syntax
* ✅ **File Operations**: Standard Unix file operations (cp, mv, rm, etc.)
* ✅ **Process Management**: Background processes, job control

### Example

```python theme={null}
from hopx_ai import Sandbox

sandbox = Sandbox.create(template="code-interpreter")

# Execute bash commands
result = sandbox.run_code("""
#!/bin/bash
echo "Current directory: $(pwd)"
echo "User: $(whoami)"
echo "Date: $(date)"

# List files
ls -la /workspace

# Process data
echo "1,2,3,4,5" | tr ',' '\\n' | awk '{sum+=$1} END {print "Sum:", sum}'
""", language="bash")

print(result.stdout)
```

**Expected Output:**

```
Current directory: /workspace
User: root
Date: Mon Jan 27 10:30:00 UTC 2025
total 8
drwxr-xr-x 2 root root 4096 Jan 27 10:30 .
drwxr-xr-x 3 root root 4096 Jan 27 10:30 ..
-rw-r--r-- 1 root root   42 Jan 27 10:30 data.txt
Sum: 15
```

### Common Use Cases

* Installing system packages with `apt-get` or `yum`
* Running build scripts and automation tasks
* Processing text files with `grep`, `sed`, `awk`
* Managing files and directories
* Running system diagnostics

## Go

Go (Golang) support enables compilation and execution of Go programs in sandboxes.

### Version

* **Go 1.21+** (varies by template)

### Features

* ✅ **Compilation**: Compile Go programs with `go build`
* ✅ **Standard Library**: Full access to Go standard library
* ✅ **Modules**: Support for Go modules and dependency management
* ✅ **Concurrency**: Full support for goroutines and channels
* ✅ **Cross-compilation**: Can compile for different platforms

### Example

```python theme={null}
from hopx_ai import Sandbox

sandbox = Sandbox.create(template="code-interpreter")

# Execute Go code
result = sandbox.run_code("""
package main

import (
    "fmt"
    "time"
)

func main() {
    fmt.Println("Hello from Go!")
    fmt.Printf("Current time: %s\\n", time.Now().Format(time.RFC3339))
    
    // Simple goroutine example
    go func() {
        time.Sleep(1 * time.Second)
        fmt.Println("Goroutine completed!")
    }()
    
    time.Sleep(2 * time.Second)
}
""", language="go")

print(result.stdout)
```

**Expected Output:**

```
Hello from Go!
Current time: 2025-01-27T10:30:00Z  # Actual timestamp will vary
Goroutine completed!
```

<Note>
  The timestamp in the output will be the actual execution time, not a fixed value. The format follows RFC3339 (e.g., `2025-01-27T10:30:00Z`).
</Note>

## Language-Specific Considerations

### Execution Timeouts

Default timeouts vary by language and execution mode:

* **Synchronous execution**: 30-60 seconds (configurable)
* **Background execution**: Up to 300 seconds (5 minutes)
* **Async execution**: Up to 3600 seconds (1 hour) with webhooks

### Memory and Resources

* Each sandbox has allocated CPU, memory, and disk resources
* Resource limits are defined by the template
* Monitor resource usage to avoid hitting limits

### Package Installation

<Tabs>
  <Tab title="Python">
    ```python theme={null}
    # Install packages during execution
    sandbox.run_code("""
    import subprocess
    subprocess.run(['pip', 'install', 'package-name'], check=True)
    """, language="python")
    ```

    Or use commands:

    ```python theme={null}
    sandbox.commands.run("pip install package-name")
    ```
  </Tab>

  <Tab title="JavaScript">
    ```javascript theme={null}
    // Install packages during execution
    await sandbox.runCode(`
    const { execSync } = require('child_process');
    execSync('npm install package-name', { stdio: 'inherit' });
    `, { language: 'javascript' });
    ```

    Or use commands:

    ```javascript theme={null}
    await sandbox.commands.run('npm install package-name');
    ```
  </Tab>

  <Tab title="Bash">
    ```python theme={null}
    sandbox.run_code("""
    apt-get update && apt-get install -y package-name
    """, language="bash")
    ```
  </Tab>
</Tabs>

### Environment Variables

All languages can access environment variables set in the sandbox:

<Tabs>
  <Tab title="Python">
    ```python theme={null}
    import os
    value = os.getenv('MY_VAR', 'default')
    ```
  </Tab>

  <Tab title="JavaScript">
    ```javascript theme={null}
    const value = process.env.MY_VAR || 'default';
    ```
  </Tab>

  <Tab title="Bash">
    ```bash theme={null}
    value=${MY_VAR:-default}
    ```
  </Tab>

  <Tab title="Go">
    ```go theme={null}
    import "os"
    value := os.Getenv("MY_VAR")
    if value == "" {
        value = "default"
    }
    ```
  </Tab>
</Tabs>

## Choosing the Right Language

<CardGroup cols={2}>
  <Card title="Data Science & Analytics" icon="bar-chart">
    Use **Python** for data analysis, machine learning, and visualization. Pre-installed packages like pandas, numpy, and matplotlib make it ideal for data work.
  </Card>

  <Card title="Web Development" icon="code">
    Use **JavaScript** for Node.js applications, API development, and web scraping. Full npm support enables rapid development.
  </Card>

  <Card title="System Automation" icon="terminal">
    Use **Bash** for system administration, file processing, and automation scripts. Perfect for DevOps tasks.
  </Card>

  <Card title="High Performance" icon="zap">
    Use **Go** for concurrent programs, network services, and performance-critical applications. Excellent for building APIs and microservices.
  </Card>
</CardGroup>

## Language Support by Template

Different templates support different languages. Check template details to see which languages are available:

```python theme={null}
from hopx_ai import Sandbox

# List available templates
templates = Sandbox.list_templates()

for template in templates:
    print(f"{template.name}: {template.language or 'Multiple'}")
```

**Expected Output:**

```
code-interpreter: Multiple
python-basic: Python
node-basic: JavaScript
ubuntu-base: Multiple
```

<Note>
  The actual templates and their languages may vary. Use `Sandbox.list_templates()` to see available templates in your account.
</Note>

## Related

* **[Code Execution](/core-concepts/code-execution/synchronous)** - Execute code in different languages
* **[Creating Sandboxes](/core-concepts/sandboxes/creating)** - Create sandboxes with language support
* **[Listing Templates](/core-concepts/templates/listing)** - Find templates with language support
* **[Quickstart Guide](/quickstart)** - Get started with code execution

## Next Steps

* Follow the [Quickstart Guide](/quickstart) to execute your first code
* Learn about [Code Execution](/core-concepts/code-execution/synchronous) features
* Explore [Rich Output Capture](/core-concepts/code-execution/rich-output) for data visualization
