Run Commands

Koyeb Sandboxes are currently in public preview.

Run Commands

Execute a command

To execute a command in your sandbox, use the exec function:

result = sandbox.exec("echo 'Hello World'")
print(result.stdout.strip())

When using sandboxes asynchronously, use await with the exec function:

result = await sandbox.exec("echo 'Hello World'")
print(result.stdout.strip())

You can run Python scripts as commands in the exec function, including multi-line Python scripts:

# Python command
result = sandbox.exec("python3 -c 'print(2 + 2)'")
print(result.stdout.strip())
 
# Multi-line Python script
result = sandbox.exec(
    '''python3 -c "
    import sys
    print(f'Python version: {sys.version.split()[0]}')
    print(f'Platform: {sys.platform}')
    "'''
)
print(result.stdout.strip())

The following shows running Python scripts with exec asynchronously:

# Python command
result = await sandbox.exec("python3 -c 'print(2 + 2)'")
print(result.stdout.strip())
 
# Multi-line Python script
result = await sandbox.exec(
    '''python3 -c "
    import sys
    print(f'Python version: {sys.version.split()[0]}')
    print(f'Platform: {sys.platform}')
    "'''
    )
print(result.stdout.strip())

Stream output

The following code shows streaming output in real time:

# Stream output in real-time
result = sandbox.exec(
    '''python3 -c "
import time
for i in range(5):
    print(f'Line {i+1}')
    time.sleep(0.5)
"''',
    on_stdout=lambda data: print(data.strip(), end=" "),
    on_stderr=lambda data: print(f"ERR: {data.strip()}"),
)
print(f"\nExit code: {result.exit_code}")

This example showcases streaming output using an asynchronous sandbox configuration:

# Stream output in real-time
result = await sandbox.exec(
    '''python3 -c "
import time
for i in range(5):
    print(f'Line {i+1}')
    time.sleep(0.5)
"''',
    on_stdout=lambda data: print(data.strip(), end=" "),
    on_stderr=lambda data: print(f"ERR: {data.strip()}"),
)
print(f"\nExit code: {result.exit_code}")

Set environment variables

To set environment variables in a Koyeb sandbox, run a command just as you would from your terminal. Use the exec function to run your command:

# Set environment variables
env_vars = {"MY_VAR": "Hello", "DEBUG": "true"}
result = sandbox.exec("env | grep MY_VAR", env=env_vars)
print(result.stdout.strip())

When using an asychronous configuration with your sandbox, you can use await:

# Set environment variables
env_vars = {"MY_VAR": "Hello", "DEBUG": "true"}
result = await sandbox.exec("env | grep MY_VAR", env=env_vars)
print(result.stdout.strip())

Manage background processes

In a code sandbox environment, background tasks are operations that run asynchronously and independently from the main execution flow of a program, allowing long-running or resource-intensive work to continue without blocking the user’s primary interaction. These tasks are especially useful when you need to perform actions such as processing files, generating images or videos, running model inferences, handling scheduled jobs, or monitoring system events without keeping the sandbox session active or delaying immediate responses. Because sandboxes are ephemeral and optimized for quick, isolated execution, background tasks ensure that work can continue reliably even if the main process ends, enabling more complex workflows while maintaining performance, responsiveness, and security within the constrained sandbox environment.

Launch a process

To launch a long-running process, use the launch_process function:

# Launch a long-running process
process_id_1 = sandbox.launch_process(
    "python3 -c 'import time; [print(f\"Process 1: {i}\") or time.sleep(1) for i in range(10)]'"
)
print(f"Launched process 1: {process_id_1}")

This starts a non-block process that continues to run in the background until it completes or is shut down. It returns the ID of the process to use as reference. Use this ID to take actions on the process like shutting it down.

When using sandboxes asynchronously, you can call launch_process with await:

# Launch a long-running process
process_id_1 = await sandbox.launch_process(
    "python3 -c 'import time; [print(f\"Process 1: {i}\") or time.sleep(1) for i in range(10)]'"
)
print(f"Launched process 1: {process_id_1}")

List processes

To list all processes that are currently running, use the list_processes function:

processes = sandbox.list_processes()
for process in processes:
    print(f"  ID: {process.id}")
    print(f"  Command: {process.command}")
    print(f"  Status: {process.status}")
    if process.pid:
        print(f"  PID: {process.pid}")
    print()

This function returns an array of processes, including the unique identifier of the process, the command that was run, and the status of the process (e.g., "running", "completed", etc).

When using sandboxes asynchronously, you can call list_processes with await:

processes = await sandbox.list_processes()
for process in processes:
    print(f"  ID: {process.id}")
    print(f"  Command: {process.command}")
    print(f"  Status: {process.status}")
    if process.pid:
        print(f"  PID: {process.pid}")
    print()

Shut down a process

To shut down a long-running process, use the kill_process function, passing the process ID:

sandbox.kill_process(process_id_1)

When using sandboxes asynchronously, you can call kill_process with await:

await sandbox.kill_process(process_id_1)

Shut down all processes

To shut down all long-running processes at once, use the kill_all_processes function:

killed_count = sandbox.kill_all_processes()
print(f"Killed {killed_count} processes")

When using sandboxes asynchronously, you can call kill_all_processes with await:

killed_count = await sandbox.kill_all_processes()
print(f"Killed {killed_count} processes")