Run shell commands in the background and return immediately. This is ideal for long-running commands that you want to monitor and manage separately.
Overview
Background command execution is perfect for:
- Long-running commands (>5 minutes)
- Server processes that need to keep running
- Commands that don’t need immediate results
- Parallel execution of multiple commands
Background commands return immediately with a process_id. Use process management to check status and manage background processes.
Starting Background Commands
Start a command in the background:
from hopx_ai import Sandbox
sandbox = Sandbox.create(template="code-interpreter")
# Start background command
result = sandbox.commands.run(
'sleep 30 && echo "Done!"',
background=True
)
# Extract process ID from output
process_id = result.stdout.split('cmd_')[-1].strip() if 'cmd_' in result.stdout else None
print(f"Process started: {process_id}")
print(f"Status: {result.stdout}")
sandbox.kill()
Checking Process Status
Check the status of background commands:
from hopx_ai import Sandbox
import time
sandbox = Sandbox.create(template="code-interpreter")
# Start background command
result = sandbox.commands.run(
'sleep 30 && echo "Task completed"',
background=True
)
# Extract process ID
process_id = result.stdout.split('cmd_')[-1].strip() if 'cmd_' in result.stdout else None
# Check status using list_processes
for i in range(5):
processes = sandbox.list_processes()
for proc in processes:
if proc.get('process_id') == process_id:
print(f"Status: {proc['status']}")
if proc['status'] == 'completed':
print(f"Output: {proc.get('stdout', '')}")
break
time.sleep(2)
sandbox.kill()
Long-Running Servers
Start long-running server processes:
from hopx_ai import Sandbox
import time
sandbox = Sandbox.create(template="code-interpreter")
# Start a web server in background
result = sandbox.commands.run(
'python -m http.server 8000',
background=True,
timeout=3600, # 1 hour
env={"PORT": "8000"}
)
process_id = result.stdout.split('cmd_')[-1].strip() if 'cmd_' in result.stdout else None
print(f"Server started: {process_id}")
# Check if server is running
time.sleep(2)
processes = sandbox.list_processes()
for proc in processes:
if proc.get('process_id') == process_id:
print(f"Server status: {proc['status']}")
sandbox.kill()
Environment Variables
Pass environment variables to background commands:
from hopx_ai import Sandbox
sandbox = Sandbox.create(template="code-interpreter")
# Start background command with environment variables
result = sandbox.commands.run(
'python -c "import os, time; print(os.getenv(\'API_KEY\')); time.sleep(60)"',
background=True,
env={
"API_KEY": "sk-123456",
"DEBUG": "true"
}
)
print(f"Process started: {result.stdout}")
sandbox.kill()
Timeout Configuration
Set timeout for background commands:
from hopx_ai import Sandbox
sandbox = Sandbox.create(template="code-interpreter")
# Start background command with 10 minute timeout
result = sandbox.commands.run(
'long_running_task.sh',
background=True,
timeout=600 # 10 minutes
)
print(f"Process started with {600}s timeout")
sandbox.kill()
Complete Example
Here’s a complete example showing background command workflow:
from hopx_ai import Sandbox
import time
sandbox = Sandbox.create(template="code-interpreter")
# Start multiple background tasks
tasks = {
'data-processing': 'python process_data.py',
'ml-training': 'python train_model.py',
'report-generation': 'python generate_report.py'
}
process_ids = {}
print("🚀 Starting background tasks...\n")
for name, command in tasks.items():
result = sandbox.commands.run(
command,
background=True,
timeout=600,
env={"TASK_NAME": name}
)
process_id = result.stdout.split('cmd_')[-1].strip() if 'cmd_' in result.stdout else None
process_ids[name] = process_id
print(f"✅ Started: {name} (ID: {process_id})")
# Monitor all processes
print("\n📊 Monitoring processes...")
while True:
all_processes = sandbox.list_processes()
active = [
p for p in all_processes
if p.get('process_id') in process_ids.values()
and p.get('status') in ['queued', 'running']
]
if not active:
break
print(f"\nActive: {len(active)}/{len(tasks)}")
for proc in active:
name = next(k for k, v in process_ids.items() if v == proc.get('process_id'))
print(f" {name}: {proc['status']}")
time.sleep(3)
# Show final results
print("\n📋 Final Status:")
all_processes = sandbox.list_processes()
for name, proc_id in process_ids.items():
proc = next((p for p in all_processes if p.get('process_id') == proc_id), None)
if proc:
status_icon = {
'completed': '✅',
'failed': '❌',
'killed': '🛑'
}.get(proc['status'], '⏳')
print(f"{status_icon} {name}: {proc['status']}")
if proc['status'] == 'completed' and proc.get('stdout'):
print(f" Output: {proc['stdout'].strip()[:50]}...")
sandbox.kill()
Best Practices
1. Extract Process IDs
Extract process IDs from the result to track and manage background commands.
2. Set Appropriate Timeouts
Set timeouts based on expected execution time. Default is 30 seconds, but increase for longer tasks.
3. Monitor Status Regularly
Check process status periodically to track progress and detect failures early.
4. Use Process Management
Use list_processes() and kill_process() to monitor and control background commands.
5. Handle Failures
Check for failed status and access stderr for error details when commands fail.
Next Steps