Retrieve environment variables from your sandbox. You can get all variables at once or fetch specific variables by name.
Overview
Getting environment variables is useful for:
- Inspecting current environment configuration
- Verifying variables are set correctly
- Accessing system and custom variables
- Debugging environment-related issues
Environment variables include both system variables (like PATH, HOME) and custom variables youβve set. Sensitive values may be masked in responses.
Get All Environment Variables
Retrieve all environment variables:
from hopx_ai import Sandbox
sandbox = Sandbox.create(template="code-interpreter")
# Get all environment variables
env = sandbox.env.get_all()
print(f"Total variables: {len(env)}")
# Access specific variables
print(f"PATH: {env.get('PATH', 'not set')}")
print(f"HOME: {env.get('HOME', 'not set')}")
sandbox.kill()
import { Sandbox } from '@hopx-ai/sdk';
const sandbox = await Sandbox.create({ template: 'code-interpreter' });
// Get all environment variables
const env = await sandbox.env.getAll();
console.log(`Total variables: ${Object.keys(env).length}`);
// Access specific variables
console.log(`PATH: ${env.PATH || 'not set'}`);
console.log(`HOME: ${env.HOME || 'not set'}`);
await sandbox.kill();
Get Specific Variable
Get a single environment variable:
from hopx_ai import Sandbox
sandbox = Sandbox.create(template="code-interpreter")
# Get a specific variable
api_key = sandbox.env.get("API_KEY")
if api_key:
print(f"API key: {api_key[:10]}...")
else:
print("API_KEY not set")
# Get with default value
db_url = sandbox.env.get("DATABASE_URL", "postgres://localhost/db")
print(f"Database URL: {db_url}")
sandbox.kill()
import { Sandbox } from '@hopx-ai/sdk';
const sandbox = await Sandbox.create({ template: 'code-interpreter' });
// Get a specific variable
const apiKey = await sandbox.env.get('API_KEY');
if (apiKey) {
console.log(`API key: ${apiKey.substring(0, 10)}...`);
} else {
console.log('API_KEY not set');
}
// Get with default value
const dbUrl = await sandbox.env.get('DATABASE_URL', 'postgres://localhost/db');
console.log(`Database URL: ${dbUrl}`);
await sandbox.kill();
List All Variables
Iterate through all environment variables:
from hopx_ai import Sandbox
sandbox = Sandbox.create(template="code-interpreter")
# Get all variables
env = sandbox.env.get_all()
# List all variables
print("Environment Variables:")
for key, value in sorted(env.items()):
# Mask sensitive values
if any(sensitive in key.upper() for sensitive in ['KEY', 'SECRET', 'PASSWORD', 'TOKEN']):
print(f" {key}=***MASKED***")
else:
print(f" {key}={value}")
sandbox.kill()
import { Sandbox } from '@hopx-ai/sdk';
const sandbox = await Sandbox.create({ template: 'code-interpreter' });
// Get all variables
const env = await sandbox.env.getAll();
// List all variables
console.log('Environment Variables:');
for (const [key, value] of Object.entries(env).sort()) {
// Mask sensitive values
const isSensitive = ['KEY', 'SECRET', 'PASSWORD', 'TOKEN'].some(
s => key.toUpperCase().includes(s)
);
if (isSensitive) {
console.log(` ${key}=***MASKED***`);
} else {
console.log(` ${key}=${value}`);
}
}
await sandbox.kill();
Filter Variables
Filter environment variables by prefix or pattern:
from hopx_ai import Sandbox
sandbox = Sandbox.create(template="code-interpreter")
# Get all variables
env = sandbox.env.get_all()
# Filter by prefix
api_vars = {k: v for k, v in env.items() if k.startswith('API_')}
print(f"API variables: {list(api_vars.keys())}")
# Filter by pattern
debug_vars = {k: v for k, v in env.items() if 'DEBUG' in k.upper()}
print(f"Debug variables: {list(debug_vars.keys())}")
# Filter custom variables (exclude system vars)
system_vars = {'PATH', 'HOME', 'USER', 'SHELL', 'PWD'}
custom_vars = {k: v for k, v in env.items() if k not in system_vars}
print(f"Custom variables: {list(custom_vars.keys())}")
sandbox.kill()
import { Sandbox } from '@hopx-ai/sdk';
const sandbox = await Sandbox.create({ template: 'code-interpreter' });
// Get all variables
const env = await sandbox.env.getAll();
// Filter by prefix
const apiVars = Object.fromEntries(
Object.entries(env).filter(([k]) => k.startsWith('API_'))
);
console.log(`API variables: ${Object.keys(apiVars)}`);
// Filter by pattern
const debugVars = Object.fromEntries(
Object.entries(env).filter(([k]) => k.toUpperCase().includes('DEBUG'))
);
console.log(`Debug variables: ${Object.keys(debugVars)}`);
// Filter custom variables (exclude system vars)
const systemVars = new Set(['PATH', 'HOME', 'USER', 'SHELL', 'PWD']);
const customVars = Object.fromEntries(
Object.entries(env).filter(([k]) => !systemVars.has(k))
);
console.log(`Custom variables: ${Object.keys(customVars)}`);
await sandbox.kill();
Check Variable Existence
Check if a variable exists:
from hopx_ai import Sandbox
sandbox = Sandbox.create(template="code-interpreter")
# Check if variable exists
api_key = sandbox.env.get("API_KEY")
if api_key:
print("API_KEY is set")
else:
print("API_KEY is not set")
# Check multiple variables
required_vars = ["API_KEY", "DATABASE_URL", "NODE_ENV"]
env = sandbox.env.get_all()
missing = [var for var in required_vars if var not in env]
if missing:
print(f"Missing variables: {missing}")
else:
print("All required variables are set")
sandbox.kill()
import { Sandbox } from '@hopx-ai/sdk';
const sandbox = await Sandbox.create({ template: 'code-interpreter' });
// Check if variable exists
const apiKey = await sandbox.env.get('API_KEY');
if (apiKey) {
console.log('API_KEY is set');
} else {
console.log('API_KEY is not set');
}
// Check multiple variables
const requiredVars = ['API_KEY', 'DATABASE_URL', 'NODE_ENV'];
const env = await sandbox.env.getAll();
const missing = requiredVars.filter(v => !(v in env));
if (missing.length > 0) {
console.log(`Missing variables: ${missing}`);
} else {
console.log('All required variables are set');
}
await sandbox.kill();
Verify Variables in Code
Verify environment variables are accessible in code execution:
from hopx_ai import Sandbox
sandbox = Sandbox.create(template="code-interpreter")
# Set some variables
sandbox.env.set("API_KEY", "sk-123")
sandbox.env.set("DEBUG", "true")
# Verify they're accessible in code
result = sandbox.run_code('''
import os
print(f"API_KEY: {os.getenv('API_KEY')}")
print(f"DEBUG: {os.getenv('DEBUG')}")
''')
print(result.stdout)
# Get variables via env API
env = sandbox.env.get_all()
print(f"\nVia API - API_KEY: {env.get('API_KEY')}")
print(f"Via API - DEBUG: {env.get('DEBUG')}")
sandbox.kill()
import { Sandbox } from '@hopx-ai/sdk';
const sandbox = await Sandbox.create({ template: 'code-interpreter' });
// Set some variables
await sandbox.env.set('API_KEY', 'sk-123');
await sandbox.env.set('DEBUG', 'true');
// Verify they're accessible in code
const result = await sandbox.runCode(`
import os
print(f"API_KEY: {os.getenv('API_KEY')}")
print(f"DEBUG: {os.getenv('DEBUG')}")
`);
console.log(result.stdout);
// Get variables via env API
const env = await sandbox.env.getAll();
console.log(`\nVia API - API_KEY: ${env.API_KEY}`);
console.log(`Via API - DEBUG: ${env.DEBUG}`);
await sandbox.kill();
Complete Example
Hereβs a complete example showing environment variable retrieval:
from hopx_ai import Sandbox
sandbox = Sandbox.create(template="code-interpreter")
# Set up environment
sandbox.env.set_all({
"API_KEY": "sk-prod-xyz",
"DATABASE_URL": "postgres://localhost/db",
"NODE_ENV": "production",
"DEBUG": "false"
})
# Get all variables
print("π All Environment Variables:")
env = sandbox.env.get_all()
for key, value in sorted(env.items()):
if any(sensitive in key.upper() for sensitive in ['KEY', 'SECRET', 'PASSWORD']):
print(f" {key}=***MASKED***")
else:
print(f" {key}={value}")
# Get specific variables
print("\nπ Specific Variables:")
api_key = sandbox.env.get("API_KEY")
print(f" API_KEY: {'Set' if api_key else 'Not set'}")
db_url = sandbox.env.get("DATABASE_URL")
print(f" DATABASE_URL: {db_url}")
node_env = sandbox.env.get("NODE_ENV", "development")
print(f" NODE_ENV: {node_env}")
# Verify in code execution
print("\nβ
Verification in Code:")
result = sandbox.run_code('''
import os
print(f"API_KEY: {os.getenv('API_KEY', 'not set')[:10]}...")
print(f"DATABASE_URL: {os.getenv('DATABASE_URL', 'not set')}")
print(f"NODE_ENV: {os.getenv('NODE_ENV', 'not set')}")
''')
print(result.stdout)
sandbox.kill()
import { Sandbox } from '@hopx-ai/sdk';
const sandbox = await Sandbox.create({ template: 'code-interpreter' });
// Set up environment
await sandbox.env.setAll({
API_KEY: 'sk-prod-xyz',
DATABASE_URL: 'postgres://localhost/db',
NODE_ENV: 'production',
DEBUG: 'false'
});
// Get all variables
console.log('π All Environment Variables:');
const env = await sandbox.env.getAll();
for (const [key, value] of Object.entries(env).sort()) {
const isSensitive = ['KEY', 'SECRET', 'PASSWORD'].some(
s => key.toUpperCase().includes(s)
);
if (isSensitive) {
console.log(` ${key}=***MASKED***`);
} else {
console.log(` ${key}=${value}`);
}
}
// Get specific variables
console.log('\nπ Specific Variables:');
const apiKey = await sandbox.env.get('API_KEY');
console.log(` API_KEY: ${apiKey ? 'Set' : 'Not set'}`);
const dbUrl = await sandbox.env.get('DATABASE_URL');
console.log(` DATABASE_URL: ${dbUrl}`);
const nodeEnv = await sandbox.env.get('NODE_ENV', 'development');
console.log(` NODE_ENV: ${nodeEnv}`);
// Verify in code execution
console.log('\nβ
Verification in Code:');
const result = await sandbox.runCode(`
import os
print(f"API_KEY: {os.getenv('API_KEY', 'not set')[:10]}...")
print(f"DATABASE_URL: {os.getenv('DATABASE_URL', 'not set')}")
print(f"NODE_ENV: {os.getenv('NODE_ENV', 'not set')}")
`);
console.log(result.stdout);
await sandbox.kill();
Best Practices
1. Use get() for Single Variables
Use env.get(key) for retrieving individual variables with optional defaults.
2. Use get_all() for Multiple Variables
Use env.get_all() when you need to access multiple variables or iterate through all.
3. Handle Missing Variables
Always check if variables exist or provide defaults when retrieving.
4. Mask Sensitive Values
When displaying environment variables, mask sensitive values (keys, secrets, passwords, tokens).
5. Verify in Code
Test that environment variables are accessible in code execution to ensure theyβre set correctly.
Next Steps