Sandbox
class Sandbox(SandboxApi)
E2B cloud sandbox is a secure and isolated cloud environment.
The sandbox allows you to:
- Access Linux OS
- Create, list, and delete files and directories
- Run commands
- Run isolated code
- Access the internet
Check docs here.
Use the Sandbox.create() to create a new sandbox.
Example:
from e2b import Sandbox
sandbox = Sandbox.create()
files
@property
def files() -> Filesystem
Module for interacting with the sandbox filesystem.
commands
@property
def commands() -> Commands
Module for running commands in the sandbox.
pty
@property
def pty() -> Pty
Module for interacting with the sandbox pseudo-terminal.
__init__
def __init__(**opts: Unpack[SandboxOpts])
:deprecated: This constructor is deprecated
Use Sandbox.create() to create a new sandbox instead.
is_running
def is_running(request_timeout: Optional[float] = None) -> bool
Check if the sandbox is running.
Arguments:
- request_timeout: Timeout for the request in seconds
Returns:
True if the sandbox is running, False otherwise
Example
sandbox = Sandbox.create()
sandbox.is_running() # Returns True
sandbox.kill()
sandbox.is_running() # Returns False
create
@classmethod
def create(cls,
           template: Optional[str] = None,
           timeout: Optional[int] = None,
           metadata: Optional[Dict[str, str]] = None,
           envs: Optional[Dict[str, str]] = None,
           secure: bool = True,
           allow_internet_access: bool = True,
           mcp: Optional[McpServer] = None,
           **opts: Unpack[ApiParams]) -> Self
Create a new sandbox.
By default, the sandbox is created from the default base sandbox template.
Arguments:
- template: Sandbox template name or ID
- timeout: Timeout for the sandbox in seconds, default to 300 seconds. The maximum time a sandbox can be kept alive is 24 hours (86_400 seconds) for Pro users and 1 hour (3_600 seconds) for Hobby users.
- metadata: Custom metadata for the sandbox
- envs: Custom environment variables for the sandbox
- secure: Envd is secured with access token and cannot be used without it, defaults to- True.
- allow_internet_access: Allow sandbox to access the internet, defaults to- True.
- mcp: MCP server to enable in the sandbox
Returns:
A Sandbox instance for the new sandbox Use this method instead of using the constructor to create a new sandbox.
connect
@overload
def connect(timeout: Optional[int] = None, **opts: Unpack[ApiParams]) -> Self
Connect to a sandbox. If the sandbox is paused, it will be automatically resumed.
Sandbox must be either running or be paused.
With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc).
Arguments:
- timeout: Timeout for the sandbox in seconds For running sandboxes, the timeout will update only if the new timeout is longer than the existing one.
Returns:
A running sandbox instance @example
sandbox = Sandbox.create()
sandbox.beta_pause()
same_sandbox = sandbox.connect()
### connect
```python
@overload
@classmethod
def connect(cls,
            sandbox_id: str,
            timeout: Optional[int] = None,
            **opts: Unpack[ApiParams]) -> Self
Connect to a sandbox. If the sandbox is paused, it will be automatically resumed.
Sandbox must be either running or be paused.
With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc).
Arguments:
- sandbox_id: Sandbox ID
- timeout: Timeout for the sandbox in seconds. For running sandboxes, the timeout will update only if the new timeout is longer than the existing one.
Returns:
A running sandbox instance @example
sandbox = Sandbox.create()
Sandbox.beta_pause(sandbox.sandbox_id)
same_sandbox = Sandbox.connect(sandbox.sandbox_id)
connect
@class_method_variant("_cls_connect")
def connect(timeout: Optional[int] = None, **opts: Unpack[ApiParams]) -> Self
Connect to a sandbox. If the sandbox is paused, it will be automatically resumed.
Sandbox must be either running or be paused.
With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc).
Arguments:
- timeout: Timeout for the sandbox in seconds. For running sandboxes, the timeout will update only if the new timeout is longer than the existing one.
Returns:
A running sandbox instance @example
sandbox = Sandbox.create()
sandbox.beta_pause()
same_sandbox = sandbox.connect()
kill
@overload
def kill(**opts: Unpack[ApiParams]) -> bool
Kill the sandbox.
Returns:
True if the sandbox was killed, False if the sandbox was not found
kill
@overload
@staticmethod
def kill(sandbox_id: str, **opts: Unpack[ApiParams]) -> bool
Kill the sandbox specified by sandbox ID.
Arguments:
- sandbox_id: Sandbox ID
Returns:
True if the sandbox was killed, False if the sandbox was not found
kill
@class_method_variant("_cls_kill")
def kill(**opts: Unpack[ApiParams]) -> bool
Kill the sandbox specified by sandbox ID.
Returns:
True if the sandbox was killed, False if the sandbox was not found
set_timeout
@overload
def set_timeout(timeout: int, **opts: Unpack[ApiParams]) -> None
Set the timeout of the sandbox.
After the timeout expires, the sandbox will be automatically killed.
This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to .set_timeout.
The maximum time a sandbox can be kept alive is 24 hours (86_400 seconds) for Pro users and 1 hour (3_600 seconds) for Hobby users.
Arguments:
- timeout: Timeout for the sandbox in seconds
set_timeout
@overload
@staticmethod
def set_timeout(sandbox_id: str, timeout: int,
                **opts: Unpack[ApiParams]) -> None
Set the timeout of the sandbox specified by sandbox ID.
After the timeout expires, the sandbox will be automatically killed.
This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to .set_timeout.
The maximum time a sandbox can be kept alive is 24 hours (86_400 seconds) for Pro users and 1 hour (3_600 seconds) for Hobby users.
Arguments:
- sandbox_id: Sandbox ID
- timeout: Timeout for the sandbox in seconds
set_timeout
@class_method_variant("_cls_set_timeout")
def set_timeout(timeout: int, **opts: Unpack[ApiParams]) -> None
Set the timeout of the sandbox.
After the timeout expires, the sandbox will be automatically killed.
This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to .set_timeout.
The maximum time a sandbox can be kept alive is 24 hours (86_400 seconds) for Pro users and 1 hour (3_600 seconds) for Hobby users.
Arguments:
- timeout: Timeout for the sandbox in seconds
get_info
@overload
def get_info(**opts: Unpack[ApiParams]) -> SandboxInfo
Get sandbox information like sandbox ID, template, metadata, started at/end at date.
Returns:
Sandbox info
get_info
@overload
@staticmethod
def get_info(sandbox_id: str, **opts: Unpack[ApiParams]) -> SandboxInfo
Get sandbox information like sandbox ID, template, metadata, started at/end at date.
Arguments:
- sandbox_id: Sandbox ID
Returns:
Sandbox info
get_info
@class_method_variant("_cls_get_info")
def get_info(**opts: Unpack[ApiParams]) -> SandboxInfo
Get sandbox information like sandbox ID, template, metadata, started at/end at date.
Returns:
Sandbox info
get_metrics
@overload
def get_metrics(start: Optional[datetime.datetime] = None,
                end: Optional[datetime.datetime] = None,
                **opts: Unpack[ApiParams]) -> List[SandboxMetrics]
Get the metrics of the current sandbox.
Arguments:
- start: Start time for the metrics, defaults to the start of the sandbox
- end: End time for the metrics, defaults to the current time
Returns:
List of sandbox metrics containing CPU, memory and disk usage information
get_metrics
@overload
@staticmethod
def get_metrics(sandbox_id: str,
                start: Optional[datetime.datetime] = None,
                end: Optional[datetime.datetime] = None,
                **opts: Unpack[ApiParams]) -> List[SandboxMetrics]
Get the metrics of the sandbox specified by sandbox ID.
Arguments:
- sandbox_id: Sandbox ID
- start: Start time for the metrics, defaults to the start of the sandbox
- end: End time for the metrics, defaults to the current time
Returns:
List of sandbox metrics containing CPU, memory and disk usage information
get_metrics
@class_method_variant("_cls_get_metrics")
def get_metrics(start: Optional[datetime.datetime] = None,
                end: Optional[datetime.datetime] = None,
                **opts: Unpack[ApiParams]) -> List[SandboxMetrics]
Get the metrics of the sandbox specified by sandbox ID.
Arguments:
- start: Start time for the metrics, defaults to the start of the sandbox
- end: End time for the metrics, defaults to the current time
Returns:
List of sandbox metrics containing CPU, memory and disk usage information
beta_create
@classmethod
def beta_create(cls,
                template: Optional[str] = None,
                timeout: Optional[int] = None,
                auto_pause: bool = False,
                metadata: Optional[Dict[str, str]] = None,
                envs: Optional[Dict[str, str]] = None,
                secure: bool = True,
                allow_internet_access: bool = True,
                mcp: Optional[McpServer] = None,
                **opts: Unpack[ApiParams]) -> Self
[BETA] This feature is in beta and may change in the future.
Create a new sandbox.
By default, the sandbox is created from the default base sandbox template.
Arguments:
- template: Sandbox template name or ID
- timeout: Timeout for the sandbox in seconds, default to 300 seconds. The maximum time a sandbox can be kept alive is 24 hours (86_400 seconds) for Pro users and 1 hour (3_600 seconds) for Hobby users.
- auto_pause: Automatically pause the sandbox after the timeout expires. Defaults to- False.
- metadata: Custom metadata for the sandbox
- envs: Custom environment variables for the sandbox
- secure: Envd is secured with access token and cannot be used without it, defaults to- True.
- allow_internet_access: Allow sandbox to access the internet, defaults to- True.
- mcp: MCP server to enable in the sandbox
Returns:
A Sandbox instance for the new sandbox Use this method instead of using the constructor to create a new sandbox.
beta_pause
@overload
def beta_pause(**opts: Unpack[ApiParams]) -> None
[BETA] This feature is in beta and may change in the future.
Pause the sandbox.
beta_pause
@overload
@classmethod
def beta_pause(cls, sandbox_id: str, **opts: Unpack[ApiParams]) -> None
[BETA] This feature is in beta and may change in the future.
Pause the sandbox specified by sandbox ID.
Arguments:
- sandbox_id: Sandbox ID
beta_pause
@class_method_variant("_cls_pause")
def beta_pause(**opts: Unpack[ApiParams]) -> None
[BETA] This feature is in beta and may change in the future.
Pause the sandbox.
Returns:
Sandbox ID that can be used to resume the sandbox
get_mcp_token
def get_mcp_token() -> Optional[str]
Get the MCP token for the sandbox.
Returns:
MCP token for the sandbox, or None if MCP is not enabled.
SandboxPaginator
class SandboxPaginator(SandboxPaginatorBase)
Paginator for listing sandboxes.
Example:
paginator = Sandbox.list()
while paginator.has_next:
    sandboxes = paginator.next_items()
    print(sandboxes)
next_items
def next_items() -> List[SandboxInfo]
Returns the next page of sandboxes.
Call this method only if has_next is True, otherwise it will raise an exception.
Returns:
List of sandboxes
WatchHandle
class WatchHandle()
Handle for watching filesystem events. It is used to get the latest events that have occurred in the watched directory.
Use .stop() to stop watching the directory.
stop
def stop()
Stop watching the directory. After you stop the watcher you won't be able to get the events anymore.
get_new_events
def get_new_events() -> List[FilesystemEvent]
Get the latest events that have occurred in the watched directory since the last call, or from the beginning of the watching, up until now.
Returns:
List of filesystem events
Filesystem
class Filesystem()
Module for interacting with the filesystem in the sandbox.
read
@overload
def read(path: str,
         format: Literal["text"] = "text",
         user: Optional[Username] = None,
         request_timeout: Optional[float] = None) -> str
Read file content as a str.
Arguments:
- path: Path to the file
- user: Run the operation as this user
- format: Format of the file content—- textby default
- request_timeout: Timeout for the request in seconds
Returns:
File content as a str
read
@overload
def read(path: str,
         format: Literal["bytes"],
         user: Optional[Username] = None,
         request_timeout: Optional[float] = None) -> bytearray
Read file content as a bytearray.
Arguments:
- path: Path to the file
- user: Run the operation as this user
- format: Format of the file content—- bytes
- request_timeout: Timeout for the request in seconds
Returns:
File content as a bytearray
read
@overload
def read(path: str,
         format: Literal["stream"],
         user: Optional[Username] = None,
         request_timeout: Optional[float] = None) -> Iterator[bytes]
Read file content as a Iterator[bytes].
Arguments:
- path: Path to the file
- user: Run the operation as this user
- format: Format of the file content—- stream
- request_timeout: Timeout for the request in seconds
Returns:
File content as an Iterator[bytes]
write
def write(path: str,
          data: Union[str, bytes, IO],
          user: Optional[Username] = None,
          request_timeout: Optional[float] = None) -> WriteInfo
Write content to a file on the path.
Writing to a file that doesn't exist creates the file. Writing to a file that already exists overwrites the file. Writing to a file at path that doesn't exist creates the necessary directories.
Arguments:
- path: Path to the file
- data: Data to write to the file, can be a- str,- bytes, or- IO.
- user: Run the operation as this user
- request_timeout: Timeout for the request in seconds
Returns:
Information about the written file
write_files
def write_files(files: List[WriteEntry],
                user: Optional[Username] = None,
                request_timeout: Optional[float] = None) -> List[WriteInfo]
Writes a list of files to the filesystem.
When writing to a file that doesn't exist, the file will get created. When writing to a file that already exists, the file will get overwritten. When writing to a file that's in a directory that doesn't exist, you'll get an error.
Arguments:
- files: list of files to write as- WriteEntryobjects, each containing- pathand- data
- user: Run the operation as this user
- request_timeout: Timeout for the request
Returns:
Information about the written files
list
def list(path: str,
         depth: Optional[int] = 1,
         user: Optional[Username] = None,
         request_timeout: Optional[float] = None) -> List[EntryInfo]
List entries in a directory.
Arguments:
- path: Path to the directory
- depth: Depth of the directory to list
- user: Run the operation as this user
- request_timeout: Timeout for the request in seconds
Returns:
List of entries in the directory
exists
def exists(path: str,
           user: Optional[Username] = None,
           request_timeout: Optional[float] = None) -> bool
Check if a file or a directory exists.
Arguments:
- path: Path to a file or a directory
- user: Run the operation as this user
- request_timeout: Timeout for the request in seconds
Returns:
True if the file or directory exists, False otherwise
get_info
def get_info(path: str,
             user: Optional[Username] = None,
             request_timeout: Optional[float] = None) -> EntryInfo
Get information about a file or directory.
Arguments:
- path: Path to a file or a directory
- user: Run the operation as this user
- request_timeout: Timeout for the request in seconds
Returns:
Information about the file or directory like name, type, and path
remove
def remove(path: str,
           user: Optional[Username] = None,
           request_timeout: Optional[float] = None) -> None
Remove a file or a directory.
Arguments:
- path: Path to a file or a directory
- user: Run the operation as this user
- request_timeout: Timeout for the request in seconds
rename
def rename(old_path: str,
           new_path: str,
           user: Optional[Username] = None,
           request_timeout: Optional[float] = None) -> EntryInfo
Rename a file or directory.
Arguments:
- old_path: Path to the file or directory to rename
- new_path: New path to the file or directory
- user: Run the operation as this user
- request_timeout: Timeout for the request in seconds
Returns:
Information about the renamed file or directory
make_dir
def make_dir(path: str,
             user: Optional[Username] = None,
             request_timeout: Optional[float] = None) -> bool
Create a new directory and all directories along the way if needed on the specified path.
Arguments:
- path: Path to a new directory. For example '/dirA/dirB' when creating 'dirB'.
- user: Run the operation as this user
- request_timeout: Timeout for the request in seconds
Returns:
True if the directory was created, False if the directory already exists
watch_dir
def watch_dir(path: str,
              user: Optional[Username] = None,
              request_timeout: Optional[float] = None,
              recursive: bool = False) -> WatchHandle
Watch directory for filesystem events.
Arguments:
- path: Path to a directory to watch
- user: Run the operation as this user
- request_timeout: Timeout for the request in seconds
- recursive: Watch directory recursively
Returns:
WatchHandle object for stopping watching directory
Commands
class Commands()
Module for executing commands in the sandbox.
list
def list(request_timeout: Optional[float] = None) -> List[ProcessInfo]
Lists all running commands and PTY sessions.
Arguments:
- request_timeout: Timeout for the request in seconds
Returns:
List of running commands and PTY sessions
kill
def kill(pid: int, request_timeout: Optional[float] = None) -> bool
Kills a running command specified by its process ID.
It uses SIGKILL signal to kill the command.
Arguments:
- pid: Process ID of the command. You can get the list of processes using- sandbox.commands.list()
- request_timeout: Timeout for the request in seconds
Returns:
True if the command was killed, False if the command was not found
send_stdin
def send_stdin(pid: int, data: str, request_timeout: Optional[float] = None)
Send data to command stdin.
:param pid Process ID of the command. You can get the list of processes using sandbox.commands.list().
:param data: Data to send to the command
:param request_timeout: Timeout for the request in seconds
run
@overload
def run(cmd: str,
        background: Union[Literal[False], None] = None,
        envs: Optional[Dict[str, str]] = None,
        user: Optional[Username] = None,
        cwd: Optional[str] = None,
        on_stdout: Optional[Callable[[str], None]] = None,
        on_stderr: Optional[Callable[[str], None]] = None,
        stdin: Optional[bool] = None,
        timeout: Optional[float] = 60,
        request_timeout: Optional[float] = None) -> CommandResult
Start a new command and wait until it finishes executing.
Arguments:
- cmd: Command to execute
- background:- Falseif the command should be executed in the foreground,- Trueif the command should be executed in the background
- envs: Environment variables used for the command
- user: User to run the command as
- cwd: Working directory to run the command
- on_stdout: Callback for command stdout output
- on_stderr: Callback for command stderr output
- stdin: If- True, the command will have a stdin stream that you can send data to using- sandbox.commands.send_stdin()
- timeout: Timeout for the command connection in seconds. Using- 0will not limit the command connection time
- request_timeout: Timeout for the request in seconds
Returns:
CommandResult result of the command execution
run
@overload
def run(cmd: str,
        background: Literal[True],
        envs: Optional[Dict[str, str]] = None,
        user: Optional[Username] = None,
        cwd: Optional[str] = None,
        on_stdout: None = None,
        on_stderr: None = None,
        stdin: Optional[bool] = None,
        timeout: Optional[float] = 60,
        request_timeout: Optional[float] = None) -> CommandHandle
Start a new command and return a handle to interact with it.
Arguments:
- cmd: Command to execute
- background:- Falseif the command should be executed in the foreground,- Trueif the command should be executed in the background
- envs: Environment variables used for the command
- user: User to run the command as
- cwd: Working directory to run the command
- stdin: If- True, the command will have a stdin stream that you can send data to using- sandbox.commands.send_stdin()
- timeout: Timeout for the command connection in seconds. Using- 0will not limit the command connection time
- request_timeout: Timeout for the request in seconds
Returns:
CommandHandle handle to interact with the running command
connect
def connect(pid: int,
            timeout: Optional[float] = 60,
            request_timeout: Optional[float] = None)
Connects to a running command.
You can use CommandHandle.wait() to wait for the command to finish and get execution results.
Arguments:
- pid: Process ID of the command to connect to. You can get the list of processes using- sandbox.commands.list()
- timeout: Timeout for the connection in seconds. Using- 0will not limit the connection time
- request_timeout: Timeout for the request in seconds
Returns:
CommandHandle handle to interact with the running command
Pty
class Pty()
Module for interacting with PTYs (pseudo-terminals) in the sandbox.
kill
def kill(pid: int, request_timeout: Optional[float] = None) -> bool
Kill PTY.
Arguments:
- pid: Process ID of the PTY
- request_timeout: Timeout for the request in seconds
Returns:
true if the PTY was killed, false if the PTY was not found
send_stdin
def send_stdin(pid: int,
               data: bytes,
               request_timeout: Optional[float] = None) -> None
Send input to a PTY.
Arguments:
- pid: Process ID of the PTY
- data: Input data to send
- request_timeout: Timeout for the request in seconds
create
def create(size: PtySize,
           user: Optional[Username] = None,
           cwd: Optional[str] = None,
           envs: Optional[Dict[str, str]] = None,
           timeout: Optional[float] = 60,
           request_timeout: Optional[float] = None) -> CommandHandle
Start a new PTY (pseudo-terminal).
Arguments:
- size: Size of the PTY
- user: User to use for the PTY
- cwd: Working directory for the PTY
- envs: Environment variables for the PTY
- timeout: Timeout for the PTY in seconds
- request_timeout: Timeout for the request in seconds
Returns:
Handle to interact with the PTY
resize
def resize(pid: int,
           size: PtySize,
           request_timeout: Optional[float] = None) -> None
Resize PTY.
Call this when the terminal window is resized and the number of columns and rows has changed.
Arguments:
- pid: Process ID of the PTY
- size: New size of the PTY
- request_timeout: Timeout for the request in secondss
CommandHandle
class CommandHandle()
Command execution handle.
It provides methods for waiting for the command to finish, retrieving stdout/stderr, and killing the command.
pid
@property
def pid()
Command process ID.
__iter__
def __iter__()
Iterate over the command output.
Returns:
Generator of command outputs
disconnect
def disconnect() -> None
Disconnect from the command.
The command is not killed, but SDK stops receiving events from the command.
You can reconnect to the command using sandbox.commands.connect method.
wait
def wait(on_pty: Optional[Callable[[PtyOutput], None]] = None,
         on_stdout: Optional[Callable[[str], None]] = None,
         on_stderr: Optional[Callable[[str], None]] = None) -> CommandResult
Wait for the command to finish and returns the result.
If the command exits with a non-zero exit code, it throws a CommandExitException.
Arguments:
- on_pty: Callback for pty output
- on_stdout: Callback for stdout output
- on_stderr: Callback for stderr output
Returns:
CommandResult result of command execution
kill
def kill() -> bool
Kills the command.
It uses SIGKILL signal to kill the command.
Returns:
Whether the command was killed successfully
SandboxApi
class SandboxApi(SandboxBase)
list
@staticmethod
def list(query: Optional[SandboxQuery] = None,
         limit: Optional[int] = None,
         next_token: Optional[str] = None,
         **opts: Unpack[ApiParams]) -> SandboxPaginator
List all running sandboxes.
Arguments:
- query: Filter the list of sandboxes by metadata or state, e.g.- SandboxListQuery(metadata={"key": "value"})or- SandboxListQuery(state=[SandboxState.RUNNING])
- limit: Maximum number of sandboxes to return per page
- next_token: Token for pagination
Returns:
List of running sandboxes