Skip to content

armgit / E2B

Public Imported from GitHub
0

Open-source, secure environment with real-world tools for enterprise-grade agents.

Sync version of python (#184)

Jakub Novák0683f042752e
diff --git a/.changeset/mighty-masks-cross.md b/.changeset/mighty-masks-cross.md
new file mode 100644
index 000000000..7cd9b7e63
--- /dev/null
+++ b/.changeset/mighty-masks-cross.md
@@ -0,0 +1,5 @@
+---
+'@e2b/python-sdk': minor
+---
+
+Add sync version of Python SDK
diff --git a/packages/python-sdk/e2b/__init__.py b/packages/python-sdk/e2b/__init__.py
index eaf762d70..3643cb524 100644
--- a/packages/python-sdk/e2b/__init__.py
+++ b/packages/python-sdk/e2b/__init__.py
@@ -1,11 +1,17 @@
from .session import (
Session,
+ SyncSession,
FilesystemOperation,
FilesystemWatcher,
FileInfo,
FilesystemEvent,
FilesystemManager,
TerminalManager,
+ SyncFilesystemWatcher,
+ SyncFilesystemManager,
+ SyncTerminalManager,
+ SyncProcessManager,
+ SyncProcess,
Terminal,
ProcessManager,
Process,
@@ -20,4 +26,5 @@ from .session import (
ProcessOutput,
TerminalOutput,
run_code,
+ run_code_sync,
)
diff --git a/packages/python-sdk/e2b/session/__init__.py b/packages/python-sdk/e2b/session/__init__.py
index 1ffb154c5..9d6bc7ac8 100644
--- a/packages/python-sdk/e2b/session/__init__.py
+++ b/packages/python-sdk/e2b/session/__init__.py
@@ -7,9 +7,27 @@ from .exception import (
SessionException,
TerminalException,
)
-from .filesystem import FileInfo, FilesystemManager
-from .filesystem_watcher import FilesystemEvent, FilesystemOperation, FilesystemWatcher
-from .main import Session
-from .process import Process, ProcessManager, ProcessMessage, ProcessOutput
-from .terminal import Terminal, TerminalManager, TerminalOutput
-from .run_code import run_code
+from .filesystem import FileInfo, FilesystemManager, SyncFilesystemManager
+from .filesystem_watcher import (
+ FilesystemEvent,
+ FilesystemOperation,
+ FilesystemWatcher,
+ SyncFilesystemWatcher,
+)
+from .main import Session, SyncSession
+from .process import (
+ Process,
+ ProcessManager,
+ ProcessMessage,
+ ProcessOutput,
+ SyncProcess,
+ SyncProcessManager,
+)
+from .run_code import run_code, run_code_sync
+from .terminal import (
+ Terminal,
+ TerminalManager,
+ TerminalOutput,
+ SyncTerminalManager,
+ SyncTerminal,
+)
diff --git a/packages/python-sdk/e2b/session/filesystem.py b/packages/python-sdk/e2b/session/filesystem.py
index 79d5aa628..11299baa8 100644
--- a/packages/python-sdk/e2b/session/filesystem.py
+++ b/packages/python-sdk/e2b/session/filesystem.py
@@ -1,12 +1,13 @@
+import asyncio
import base64
import logging
-from typing import Any, List, Optional
+from typing import Any, List, Optional, Type, Union
from pydantic import BaseModel
from e2b.constants import TIMEOUT
from e2b.session.exception import FilesystemException, RpcException
-from e2b.session.filesystem_watcher import FilesystemWatcher
+from e2b.session.filesystem_watcher import FilesystemWatcher, SyncFilesystemWatcher
from e2b.session.session_connection import SessionConnection
from e2b.utils.filesystem import resolve_path
@@ -22,11 +23,8 @@ class FileInfo(BaseModel):
name: str
-class FilesystemManager:
- """
- Filesystem manager is used to read, write, remove and list files and directories in the environment.
- """
-
+class BaseFilesystemManager:
+ _watcher_model = Union[Type[FilesystemWatcher], Type[SyncFilesystemWatcher]]
_service_name = "filesystem"
def __init__(self, session: SessionConnection):
@@ -167,6 +165,26 @@ class FilesystemManager:
except RpcException as e:
raise FilesystemException(e.message) from e
+ async def watch_dir(
+ self, path: str
+ ) -> Union[FilesystemWatcher, SyncFilesystemWatcher]:
+ logger.debug(f"Watching directory {path}")
+
+ path = resolve_path(path, self.cwd)
+ return self._watcher_model(
+ connection=self._session,
+ path=path,
+ service_name=self._service_name,
+ )
+
+
+class FilesystemManager(BaseFilesystemManager):
+ """
+ Filesystem manager is used to read, write, remove and list files and directories in the environment.
+ """
+
+ _watcher_model = FilesystemWatcher
+
async def watch_dir(self, path: str) -> FilesystemWatcher:
"""
Watches directory for filesystem events.
@@ -175,11 +193,97 @@ class FilesystemManager:
:return: New watcher
"""
- logger.debug(f"Watching directory {path}")
+ return await super().watch_dir(path)
- path = resolve_path(path, self.cwd)
- return FilesystemWatcher(
- connection=self._session,
- path=path,
- service_name=self._service_name,
- )
+
+class SyncFilesystemManager(BaseFilesystemManager):
+ """
+ Filesystem manager is used to read, write, remove and list files and directories in the environment.
+ """
+
+ _watcher_model = SyncFilesystemWatcher
+
+ def __init__(self, session: SessionConnection, loop: asyncio.AbstractEventLoop):
+ super().__init__(session)
+ self._loop = loop
+
+ def read_bytes(self, path: str) -> bytes:
+ """
+ Reads the whole content of a file as a byte array.
+ This can be used when you cannot represent the data as an UTF-8 string.
+
+ :param path: path to a file
+ :return: byte array representing the content of a file
+ """
+ return self._loop.run_until_complete(super().read_bytes(path))
+
+ def write_bytes(self, path: str, content: bytes) -> None:
+ """
+ Writes content to a file as a byte array.
+ This can be used when you cannot represent the data as an UTF-8 string.
+
+ :param path: path to a file
+ :param content: byte array representing the content to write
+ """
+ return self._loop.run_until_complete(super().write_bytes(path, content))
+
+ def read(self, path: str, timeout: Optional[float] = TIMEOUT) -> str:
+ """
+ Reads the whole content of a file as an array of bytes.
+
+ :param path: Path to a file
+ :param timeout: Timeout for the call
+ :return: Content of a file
+ """
+ return self._loop.run_until_complete(super().read(path, timeout))
+
+ def write(
+ self, path: str, content: str, timeout: Optional[float] = TIMEOUT
+ ) -> None:
+ """
+ Writes content to a file.
+
+ :param path: Path to a file
+ :param content: Content to write
+ :param timeout: Specify the duration, in seconds to give the method to finish its execution before it times out (default is 60 seconds). If set to None, the method will continue to wait until it completes, regardless of time
+ """
+ return self._loop.run_until_complete(super().write(path, content, timeout))
+
+ def remove(self, path: str, timeout: Optional[float] = TIMEOUT) -> None:
+ """
+ Removes a file or a directory.
+
+ :param path: Path to a file or a directory
+ :param timeout: Specify the duration, in seconds to give the method to finish its execution before it times out (default is 60 seconds). If set to None, the method will continue to wait until it completes, regardless of time
+ """
+ return self._loop.run_until_complete(super().remove(path, timeout))
+
+ def list(self, path: str, timeout: Optional[float] = TIMEOUT) -> List[FileInfo]:
+ """
+ List files in a directory.
+
+ :param path: Path to a directory
+ :param timeout: Specify the duration, in seconds to give the method to finish its execution before it times out (default is 60 seconds). If set to None, the method will continue to wait until it completes, regardless of time
+
+ :return: Array of files in a directory
+ """
+ return self._loop.run_until_complete(super().list(path, timeout))
+
+ def make_dir(self, path: str, timeout: Optional[float] = TIMEOUT) -> None:
+ """
+ Creates a new directory and all directories along the way if needed on the specified path.
+
+ :param path: Path to a new directory. For example '/dirA/dirB' when creating 'dirB'
+ :param timeout: Specify the duration, in seconds to give the method to finish its execution before it times out (default is 60 seconds). If set to None, the method will continue to wait until it completes, regardless of time
+ """
+ return self._loop.run_until_complete(super().make_dir(path, timeout))
+
+ def watch_dir(self, path: str) -> SyncFilesystemWatcher:
+ """
+ Watches directory for filesystem events.
+
+ :param path: Path to a directory that will be watched
+
+ :return: New watcher
+ """
+ return self._loop.run_until_complete(super().watch_dir(path))
diff --git a/packages/python-sdk/e2b/session/filesystem_watcher.py b/packages/python-sdk/e2b/session/filesystem_watcher.py
index 8cf761fb4..d3579564a 100644
--- a/packages/python-sdk/e2b/session/filesystem_watcher.py
+++ b/packages/python-sdk/e2b/session/filesystem_watcher.py
@@ -2,10 +2,11 @@ import logging
from enum import Enum
from typing import Any, Awaitable, Callable, Optional, Set
+from pydantic import BaseModel
+
from e2b.constants import TIMEOUT
from e2b.session.exception import FilesystemException, RpcException
from e2b.session.session_connection import SessionConnection
-from pydantic import BaseModel
logger = logging.getLogger(__name__)
@@ -106,3 +107,28 @@ class FilesystemWatcher:
def _handle_filesystem_events(self, event: FilesystemEvent) -> None:
for listener in self._listeners:
listener(event)
+
+
+class SyncFilesystemWatcher(FilesystemWatcher):
+ def __init__(
+ self,
+ connection: SessionConnection,
+ path: str,
+ service_name: str,
+ ):
+ super().__init__(connection, path, service_name)
+ self._loop = connection._loop
+
+ def start(self, timeout: Optional[float] = TIMEOUT) -> None:
+ """
+ Starts the filesystem watcher.
+
+ :param timeout: Specify the duration, in seconds to give the method to finish its execution before it times out (default is 60 seconds). If set to None, the method will continue to wait until it completes, regardless of time
+ """
+ return self._loop.run_until_complete(super().start(timeout))
+
+ def stop(self) -> None:
+ """
+ Stops the filesystem watcher.
+ """
+ return self._loop.run_until_complete(super().stop())
diff --git a/packages/python-sdk/e2b/session/main.py b/packages/python-sdk/e2b/session/main.py
index f718ef65c..d4ef364ef 100644
--- a/packages/python-sdk/e2b/session/main.py
+++ b/packages/python-sdk/e2b/session/main.py
@@ -1,3 +1,4 @@
+import asyncio
import logging
from typing import Any, Callable, List, Literal, Optional, Union
@@ -6,10 +7,10 @@ from async_timeout import timeout as async_timeout
from e2b.constants import TIMEOUT
from e2b.session.code_snippet import CodeSnippetManager, OpenPort
from e2b.session.env_vars import EnvVars
-from e2b.session.filesystem import FilesystemManager
-from e2b.session.process import ProcessManager
+from e2b.session.filesystem import FilesystemManager, SyncFilesystemManager
+from e2b.session.process import ProcessManager, SyncProcessManager
from e2b.session.session_connection import SessionConnection
-from e2b.session.terminal import TerminalManager
+from e2b.session.terminal import TerminalManager, SyncTerminalManager
logger = logging.getLogger(__name__)
@@ -40,21 +41,21 @@ class Session(SessionConnection):
"""
@property
- def process(self):
+ def process(self) -> ProcessManager:
"""
Process manager used to run commands.
"""
return self._process
@property
- def terminal(self):
+ def terminal(self) -> TerminalManager:
"""
Terminal manager used to create interactive terminals.
"""
return self._terminal
@property
- def filesystem(self):
+ def filesystem(self) -> FilesystemManager:
"""
Filesystem manager used to manage files.
"""
@@ -140,8 +141,11 @@ class Session(SessionConnection):
self._process._close()
async def close(self) -> None:
+ """
+ Closes the session.
+ """
await super().close()
- self._close()
+ await self._close()
async def __aenter__(self):
await self.open()
@@ -204,5 +208,151 @@ class Session(SessionConnection):
_debug_dev_env=_debug_dev_env,
)
await session.open(timeout=timeout)
+ return session
+
+
+class SyncSession(Session):
+ """
+ E2B cloud environment gives your agent a full cloud development environment that's sandboxed. That means:
+
+ - Access to Linux OS
+ - Using filesystem (create, list, and delete files and dirs)
+ - Run processes
+ - Sandboxed - you can run any code
+ - Access to the internet
+
+ These cloud environments are meant to be used for agents. Like a sandboxed playgrounds, where the agent can do whatever it wants.
+ """
+
+ def __init__(
+ self,
+ id: Union[Environment, str],
+ api_key: Optional[str],
+ cwd: Optional[str] = None,
+ env_vars: Optional[EnvVars] = None,
+ on_scan_ports: Optional[Callable[[List[OpenPort]], Any]] = None,
+ on_stdout: Optional[Callable[[str], Any]] = None,
+ on_stderr: Optional[Callable[[str], Any]] = None,
+ on_exit: Optional[Callable[[int], Any]] = None,
+ _debug_hostname: Optional[str] = None,
+ _debug_port: Optional[int] = None,
+ _debug_dev_env: Optional[Literal["remote", "local"]] = None,
+ ):
+ super().__init__(
+ id=id,
+ api_key=api_key,
+ cwd=cwd,
+ env_vars=env_vars,
+ on_scan_ports=on_scan_ports,
+ on_stdout=on_stdout,
+ on_stderr=on_stderr,
+ on_exit=on_exit,
+ _debug_hostname=_debug_hostname,
+ _debug_port=_debug_port,
+ _debug_dev_env=_debug_dev_env,
+ )
+ self._loop = asyncio.get_event_loop()
+ asyncio.set_event_loop(self._loop)
+ self._process = SyncProcessManager(self, self._loop)
+ self._filesystem = SyncFilesystemManager(self, self._loop)
+ self._terminal = SyncTerminalManager(self, self._loop)
+
+ @property
+ def process(self) -> SyncProcessManager:
+ """
+ Process manager used to run commands.
+ """
+ return self._process
+
+ @property
+ def terminal(self) -> SyncTerminalManager:
+ """
+ Terminal manager used to create interactive terminals.
+ """
+ return self._terminal
+
+ @property
+ def filesystem(self) -> SyncFilesystemManager:
+ """
+ Filesystem manager used to manage files.
+ """
+ return self._filesystem
+
+ def open(self, timeout: Optional[float] = TIMEOUT):
+ """
+ Opens the session.
+ """
+ return self._loop.run_until_complete(super().open(timeout))
+
+ def _close_services(self):
+ self._terminal._close()
+ self._process._close()
+
+ def close(self) -> None:
+ """
+ Closes the session.
+ """
+ self._loop.run_until_complete(super().close())
+
+ def __enter__(self, timeout: Optional[float] = TIMEOUT):
+ self.open(timeout)
+ return self
+
+ def __exit__(self, exc_type, exc_value, traceback):
+ self.close()
+
+ @classmethod
+ def create(
+ cls,
+ id: Union[Environment, str],
+ api_key: Optional[str] = None,
+ cwd: Optional[str] = None,
+ env_vars: Optional[EnvVars] = None,
+ on_scan_ports: Optional[Callable[[List[OpenPort]], Any]] = None,
+ on_stdout: Optional[Callable[[str], Any]] = None,
+ on_stderr: Optional[Callable[[str], Any]] = None,
+ on_exit: Optional[Callable[[int], Any]] = None,
+ timeout: Optional[float] = TIMEOUT,
+ _debug_hostname: Optional[str] = None,
+ _debug_port: Optional[int] = None,
+ _debug_dev_env: Optional[Literal["remote", "local"]] = None,
+ ):
+ """
+ Creates a new cloud environment session.
+
+ :param id: ID of the environment or the environment type template.
+ Can be one of the following environment type templates or a custom environment ID:
+ - `Nodejs`
+ - `Bash`
+ - `Python`
+ - `Java`
+ - `Go`
+ - `Rust`
+ - `PHP`
+ - `Perl`
+ - `DotNET`
+ :param api_key: The API key to use
+ :param cwd: The current working directory to use
+ :param env_vars: Environment variables to set
+ :param on_scan_ports: A callback to handle opened ports
+ :param on_stdout: A default callback that is called when stdout with a newline is received from the process
+ :param on_stderr: A default callback that is called when stderr with a newline is received from the process
+ :param on_exit: A default callback that is called when the process exits
+ :param timeout: Specify the duration, in seconds to give the method to finish its execution before it times out (default is 60 seconds). If set to None, the method will continue to wait until it completes, regardless of time
+ """
+ session = cls(
+ id=id,
+ api_key=api_key,
+ cwd=cwd,
+ env_vars=env_vars,
+ on_scan_ports=on_scan_ports,
+ on_stdout=on_stdout,
+ on_stderr=on_stderr,
+ on_exit=on_exit,
+ _debug_hostname=_debug_hostname,
+ _debug_port=_debug_port,
+ _debug_dev_env=_debug_dev_env,
+ )
+ session.open(timeout=timeout)
return session
diff --git a/packages/python-sdk/e2b/session/process.py b/packages/python-sdk/e2b/session/process.py
index 84871a44f..6a9edd4dd 100644
--- a/packages/python-sdk/e2b/session/process.py
+++ b/packages/python-sdk/e2b/session/process.py
@@ -1,7 +1,20 @@
import asyncio
import logging
+import warnings
+from abc import ABC
from asyncio.exceptions import TimeoutError
-from typing import Any, Awaitable, Callable, ClassVar, Coroutine, Dict, List, Optional
+from typing import (
+ Any,
+ Awaitable,
+ Callable,
+ ClassVar,
+ Coroutine,
+ Dict,
+ List,
+ Optional,
+ Union,
+ Type,
+)
import async_timeout
from pydantic import BaseModel
@@ -74,6 +87,20 @@ class Process:
A process running in the environment.
"""
+ def __init__(
+ self,
+ process_id: str,
+ session: SessionConnection,
+ trigger_exit: Callable[[], Coroutine[Any, Any, None]],
+ finished: Awaitable[ProcessOutput],
+ output: ProcessOutput,
+ ):
+ self._process_id = process_id
+ self._session = session
+ self._trigger_exit = trigger_exit
+ self._finished = finished
+ self._output = output
+
@property
def output(self) -> ProcessOutput:
"""
@@ -125,21 +152,19 @@ class Process:
return self._process_id
def __await__(self):
+ """
+ Deprecated, use wait instead.
+ """
+ warnings.warn(
+ "Use wait instead of just calling await on Process", DeprecationWarning
+ )
return self._finished.__await__()
- def __init__(
- self,
- process_id: str,
- session: SessionConnection,
- trigger_exit: Callable[[], Coroutine[Any, Any, None]],
- finished: Awaitable[ProcessOutput],
- output: ProcessOutput,
- ):
- self._process_id = process_id
- self._session = session
- self._trigger_exit = trigger_exit
- self._finished = finished
- self._output = output
+ async def wait(self):
+ """
+ Waits for the process to exit.
+ """
+ return await self._finished
async def send_stdin(self, data: str, timeout: Optional[float] = TIMEOUT) -> None:
"""
@@ -173,12 +198,42 @@ class Process:
await self._trigger_exit()
-class ProcessManager:
+class SyncProcess(Process):
+ @property
+ def _loop(self):
+ return self._session._loop
+
+ def wait(self):
+ """
+ Waits for the process to exit.
+ """
+ return self._loop.run_until_complete(super().wait())
+
+ def send_stdin(self, data: str, timeout: Optional[float] = TIMEOUT) -> None:
+ """
+ Sends data to the process stdin.
+
+ :param data: Data to send
+ :param timeout: Specify the duration, in seconds to give the method to finish its execution before it times out (default is 60 seconds). If set to None, the method will continue to wait until it completes, regardless of time
+ """
+ return self._loop.run_until_complete(super().send_stdin(data, timeout))
+
+ def kill(self, timeout: Optional[float] = TIMEOUT) -> None:
+ """
+ Kills the process.
+
+ :param timeout: Specify the duration, in seconds to give the method to finish its execution before it times out (default is 60 seconds). If set to None, the method will continue to wait until it completes, regardless of time
+ """
+ return self._loop.run_until_complete(super().kill(timeout))
+
+
+class BaseProcessManager(ABC):
"""
Manager for starting and interacting with processes in the environment.
"""
_service_name = "process"
+ _process_model: Union[Type[Process], Type[SyncProcess]]
def __init__(
self,
@@ -210,24 +265,7 @@ class ProcessManager:
rootdir: str = "", # DEPRECATED
process_id: Optional[str] = None,
timeout: Optional[float] = TIMEOUT,
- ) -> Process:
- """
- Starts a process in the environment.
-
- :param cmd: The command to run
- :param on_stdout: A callback that is called when stdout with a newline is received from the process
- :param on_stderr: A callback that is called when stderr with a newline is received from the process
- :param on_exit: A callback that is called when the process exits
- :param env_vars: A dictionary of environment variables to set for the process
- :param cwd: The root directory for the process
- :param rootdir: (DEPRECATED - use cwd) The root directory for the process
- .. deprecated:: 0.3.2
- Use cwd instead.
- :param process_id: The process id to use for the process. If not provided, a random id is generated
- :param timeout: Specify the duration, in seconds to give the method to finish its execution before it times out (default is 60 seconds). If set to None, the method will continue to wait until it completes, regardless of time
-
- :return: A process object
- """
+ ) -> Union[Process, SyncProcess]:
logger.info(f"Starting process (id: {process_id}): {cmd}")
async with async_timeout.timeout(timeout):
env_vars = env_vars or {}
@@ -346,7 +384,7 @@ class ProcessManager:
],
)
logger.info(f"Started process (id: {process_id})")
- return Process(
+ return self._process_model(
output=output,
session=self._session,
process_id=process_id,
@@ -360,3 +398,111 @@ class ProcessManager:
logger.error(f"Timeout error during starting the process: {cmd}")
await trigger_exit()
raise e
+
+
+class ProcessManager(BaseProcessManager):
+ _process_model = Process
+
+ async def start(
+ self,
+ cmd: str,
+ on_stdout: Optional[Callable[[ProcessMessage], Any]] = None,
+ on_stderr: Optional[Callable[[ProcessMessage], Any]] = None,
+ on_exit: Optional[Callable[[], Any]] = None,
+ env_vars: Optional[EnvVars] = None,
+ cwd: str = "",
+ rootdir: str = "", # DEPRECATED
+ process_id: Optional[str] = None,
+ timeout: Optional[float] = TIMEOUT,
+ ) -> Process:
+ """
+ Starts a process in the environment.
+
+ :param cmd: The command to run
+ :param on_stdout: A callback that is called when stdout with a newline is received from the process
+ :param on_stderr: A callback that is called when stderr with a newline is received from the process
+ :param on_exit: A callback that is called when the process exits
+ :param env_vars: A dictionary of environment variables to set for the process
+ :param cwd: The root directory for the process
+ :param rootdir: (DEPRECATED - use cwd) The root directory for the process
+ .. deprecated:: 0.3.2
+ Use cwd instead.
+ :param process_id: The process id to use for the process. If not provided, a random id is generated
+ :param timeout: Specify the duration, in seconds to give the method to finish its execution before it times out (default is 60 seconds). If set to None, the method will continue to wait until it completes, regardless of time
+
+ :return: A process object
+ """
+ return await super().start(
+ cmd=cmd,
+ on_stdout=on_stdout,
+ on_stderr=on_stderr,
+ on_exit=on_exit,
+ env_vars=env_vars,
+ cwd=cwd,
+ rootdir=rootdir,
+ process_id=process_id,
+ timeout=timeout,
+ )
+
+
+class SyncProcessManager(BaseProcessManager):
+ _process_model = SyncProcess
+
+ def __init__(
+ self,
+ session: SessionConnection,
+ loop: asyncio.AbstractEventLoop,
+ on_stdout: Optional[Callable[[ProcessMessage], Any]] = None,
+ on_stderr: Optional[Callable[[ProcessMessage], Any]] = None,
+ on_exit: Optional[Callable[[], Any]] = None,
+ ):
+ super().__init__(
+ session=session,
+ on_stdout=on_stdout,
+ on_stderr=on_stderr,
+ on_exit=on_exit,
+ )
+ self._loop = loop
+
+ def start(
+ self,
+ cmd: str,
+ on_stdout: Optional[Callable[[ProcessMessage], Any]] = None,
+ on_stderr: Optional[Callable[[ProcessMessage], Any]] = None,
+ on_exit: Optional[Callable[[], Any]] = None,
+ env_vars: Optional[EnvVars] = None,
+ cwd: str = "",
+ rootdir: str = "", # DEPRECATED
+ process_id: Optional[str] = None,
+ timeout: Optional[float] = TIMEOUT,
+ ) -> SyncProcess:
+ """
+ Starts a process in the environment.
+
+ :param cmd: The command to run
+ :param on_stdout: A callback that is called when stdout with a newline is received from the process
+ :param on_stderr: A callback that is called when stderr with a newline is received from the process
+ :param on_exit: A callback that is called when the process exits
+ :param env_vars: A dictionary of environment variables to set for the process
+ :param cwd: The root directory for the process
+ :param rootdir: (DEPRECATED - use cwd) The root directory for the process
+ .. deprecated:: 0.3.2
+ Use cwd instead.
+ :param process_id: The process id to use for the process. If not provided, a random id is generated
+ :param timeout: Specify the duration, in seconds to give the method to finish its execution before it times out (default is 60 seconds). If set to None, the method will continue to wait until it completes, regardless of time
+
+ :return: A process object
+ """
+ return self._loop.run_until_complete(
+ super().start(
+ cmd=cmd,
+ on_stdout=on_stdout,
+ on_stderr=on_stderr,
+ on_exit=on_exit,
+ env_vars=env_vars,
+ cwd=cwd,
+ rootdir=rootdir,
+ process_id=process_id,
+ timeout=timeout,
+ )
+ )
diff --git a/packages/python-sdk/e2b/session/run_code.py b/packages/python-sdk/e2b/session/run_code.py
index e7956388d..7fcd528b6 100644
--- a/packages/python-sdk/e2b/session/run_code.py
+++ b/packages/python-sdk/e2b/session/run_code.py
@@ -1,3 +1,4 @@
+import asyncio
from os import getenv
from typing import Literal, Union, Optional
@@ -58,3 +59,24 @@ async def run_code(
await session.close()
return proc.output.stdout, proc.output.stderr
+
+
+def run_code_sync(
+ runtime: Union[CodeRuntime, str],
+ code: str,
+ api_key: Optional[str] = None,
+):
+ """
+ Runs code in a sandboxed cloud playground and return the stdout and stderr
+ `run_ode` wraps the `Session` class and provides a simple interface for running code in a sandboxed environment
+ without any need to manage lifecycle of the session.
+ `run_code` automatically loads the E2B API key from the `E2B_API_KEY` environment variable.
+
+ :param runtime: The runtime to run the code in. One of "Node16" or "Python3".
+ :param code: The code to run
+ :param api_key: The E2B API key to use. If not provided, the `E2B_API_KEY` environment variable is used.
+
+ :return: A string touple of stdout and stderr
+ """
+ loop = asyncio.get_event_loop()
+ return loop.run_until_complete(run_code(runtime, code, api_key))
diff --git a/packages/python-sdk/e2b/session/session_connection.py b/packages/python-sdk/e2b/session/session_connection.py
index ea9f90082..6ebf60031 100644
--- a/packages/python-sdk/e2b/session/session_connection.py
+++ b/packages/python-sdk/e2b/session/session_connection.py
@@ -126,6 +126,10 @@ class SessionConnection:
"""
Close the session and unsubscribe from all the subscriptions.
"""
+ await self._close()
+ logger.info(f"Session closed")
+
+ async def _close(self):
if self._is_open and self._session:
logger.info(
f"Closing session {self._session.code_snippet_id} (id: {self._session.session_id})"
@@ -134,10 +138,6 @@ class SessionConnection:
if self._rpc:
await self._rpc.close()
- self._close()
- logger.info(f"Session closed")
-
- def _close(self):
if self._on_close_child:
self._on_close_child()
@@ -195,13 +195,13 @@ class SessionConnection:
"No session to stop refreshing. Session was not created"
)
- await self.close()
+ await self._close()
refresh_handler = asyncio.create_task(refresh_cleanup())
self._process_cleanup.append(refresh_handler.cancel)
except Exception as e:
logger.error(f"Failed to acquire session")
- await self.close()
+ await self._close()
raise e
hostname = self.get_hostname(self._debug_port or WS_PORT)
@@ -216,7 +216,7 @@ class SessionConnection:
)
await self._rpc.connect()
except Exception as e:
- await self.close()
+ await self._close()
raise e
async def _call(
diff --git a/packages/python-sdk/e2b/session/terminal.py b/packages/python-sdk/e2b/session/terminal.py
index 7de811c51..1d18a2e67 100644
--- a/packages/python-sdk/e2b/session/terminal.py
+++ b/packages/python-sdk/e2b/session/terminal.py
@@ -1,6 +1,8 @@
import asyncio
import logging
-from typing import Any, Awaitable, Callable, Coroutine, List, Optional
+import warnings
+from abc import ABC
+from typing import Any, Awaitable, Callable, Coroutine, List, Optional, Union, Type
import async_timeout
from pydantic import BaseModel
@@ -56,8 +58,17 @@ class Terminal:
return self._terminal_id
def __await__(self):
+ warnings.warn(
+ """'await terminal' is deprecated, use 'await terminal.wait()' instead"""
+ )
return self.finished.__await__()
+ async def wait(self):
+ """
+ Waits till the terminal session exits.
+ """
+ return await self.finished
+
def __init__(
self,
terminal_id: str,
@@ -127,12 +138,64 @@ class Terminal:
await self._trigger_exit()
-class TerminalManager:
+class SyncTerminal(Terminal):
+ """
+ Terminal session.
+ """
+
+ def __init__(
+ self,
+ terminal_id: str,
+ session: SessionConnection,
+ trigger_exit: Callable[[], Coroutine[Any, Any, None]],
+ finished: Awaitable[TerminalOutput],
+ output: TerminalOutput,
+ loop: asyncio.AbstractEventLoop,
+ ):
+ super().__init__(terminal_id, session, trigger_exit, finished, output)
+ self._loop = loop
+
+ def wait(self):
+ """
+ Waits till the terminal session exits.
+ """
+ return self._loop.run_until_complete(super().wait())
+
+ def send_data(self, data: str, timeout: Optional[float] = TIMEOUT) -> None:
+ """
+ Sends data to the terminal standard input.
+
+ :param data: Data to send
+ :param timeout: Specify the duration, in seconds to give the method to finish its execution before it times out (default is 60 seconds). If set to None, the method will continue to wait until it completes, regardless of time
+ """
+ return self._loop.run_until_complete(super().send_data(data, timeout))
+
+ def resize(self, cols: int, rows: int, timeout: Optional[float] = TIMEOUT) -> None:
+ """
+ Resizes the terminal tty.
+
+ :param cols: Number of columns
+ :param rows: Number of rows
+ :param timeout: Specify the duration, in seconds to give the method to finish its execution before it times out (default is 60 seconds). If set to None, the method will continue to wait until it completes, regardless of time
+ """
+ return self._loop.run_until_complete(super().resize(cols, rows, timeout))
+
+ def kill(self, timeout: Optional[float] = TIMEOUT) -> None:
+ """
+ Kill the terminal session.
+
+ :param timeout: Specify the duration, in seconds to give the method to finish its execution before it times out (default is 60 seconds). If set to None, the method will continue to wait until it completes, regardless of time
+ """
+ return self._loop.run_until_complete(super().kill(timeout))
+
+
+class BaseTerminalManager(ABC):
"""
Manager for starting and interacting with terminal sessions in the environment.
"""
_service_name = "terminal"
+ _terminal_class: Union[Type[Terminal], Type[SyncTerminal]]
def __init__(self, session: SessionConnection):
self._session = session
@@ -155,23 +218,7 @@ class TerminalManager:
cmd: Optional[str] = None,
env_vars: Optional[EnvVars] = None,
timeout: Optional[float] = TIMEOUT,
- ) -> Terminal:
- """
- Start a new terminal session.
-
- :param on_data: Callback that will be called when the terminal sends data
- :param cwd: Working directory where will the terminal start
- :param terminal_id: Unique identifier of the terminal session
- :param on_exit: Callback that will be called when the terminal exits
- :param cols: Number of columns the terminal will have. This affects rendering
- :param rows: Number of rows the terminal will have. This affects rendering
- :param cmd: If the `cmd` parameter is defined it will be executed as a command
- and this terminal session will exit when the command exits
- :param env_vars: Environment variables that will be accessible inside of the terminal
- :param timeout: Specify the duration, in seconds to give the method to finish its execution before it times out (default is 60 seconds). If set to None, the method will continue to wait until it completes, regardless of time
-
- :return: Terminal session
- """
+ ) -> Union[Terminal, SyncTerminal]:
async with async_timeout.timeout(timeout):
env_vars = self._session.env_vars.update(env_vars or {})
@@ -248,7 +295,7 @@ class TerminalManager:
],
timeout=timeout,
)
- return Terminal(
+ return self._terminal_class(
terminal_id=terminal_id,
session=self._session,
trigger_exit=trigger_exit,
@@ -262,3 +309,101 @@ class TerminalManager:
logger.error(f"Timeout error during starting the terminal: {cmd}")
await trigger_exit()
raise
+
+
+class TerminalManager(BaseTerminalManager):
+ _terminal_class = Terminal
+
+ async def start(
+ self,
+ on_data: Callable[[str], Any],
+ cols: int,
+ rows: int,
+ cwd: str = "",
+ terminal_id: Optional[str] = None,
+ on_exit: Optional[Callable[[], Any]] = None,
+ cmd: Optional[str] = None,
+ env_vars: Optional[EnvVars] = None,
+ timeout: Optional[float] = TIMEOUT,
+ ) -> Union[Terminal, SyncTerminal]:
+ """
+ Start a new terminal session.
+
+ :param on_data: Callback that will be called when the terminal sends data
+ :param cwd: Working directory where will the terminal start
+ :param terminal_id: Unique identifier of the terminal session
+ :param on_exit: Callback that will be called when the terminal exits
+ :param cols: Number of columns the terminal will have. This affects rendering
+ :param rows: Number of rows the terminal will have. This affects rendering
+ :param cmd: If the `cmd` parameter is defined it will be executed as a command
+ and this terminal session will exit when the command exits
+ :param env_vars: Environment variables that will be accessible inside of the terminal
+ :param timeout: Specify the duration, in seconds to give the method to finish its execution before it times out (default is 60 seconds). If set to None, the method will continue to wait until it completes, regardless of time
+
+ :return: Terminal session
+ """
+ return await super().start(
+ on_data,
+ cols,
+ rows,
+ cwd,
+ terminal_id,
+ on_exit,
+ cmd,
+ env_vars,
+ timeout,
+ )
+
+
+class SyncTerminalManager(BaseTerminalManager):
+ """
+ Manager for starting and interacting with terminal sessions in the environment.
+ """
+
+ _terminal_class = SyncTerminal
+
+ def __init__(self, session: SessionConnection, loop: asyncio.AbstractEventLoop):
+ super().__init__(session)
+ self._loop = loop
+
+ def start(
+ self,
+ on_data: Callable[[str], Any],
+ cols: int,
+ rows: int,
+ cwd: str = "",
+ terminal_id: Optional[str] = None,
+ on_exit: Optional[Callable[[], Any]] = None,
+ cmd: Optional[str] = None,
+ env_vars: Optional[EnvVars] = None,
+ timeout: Optional[float] = TIMEOUT,
+ ) -> SyncTerminal:
+ """
+ Start a new terminal session.
+
+ :param on_data: Callback that will be called when the terminal sends data
+ :param cwd: Working directory where will the terminal start
+ :param terminal_id: Unique identifier of the terminal session
+ :param on_exit: Callback that will be called when the terminal exits
+ :param cols: Number of columns the terminal will have. This affects rendering
+ :param rows: Number of rows the terminal will have. This affects rendering
+ :param cmd: If the `cmd` parameter is defined it will be executed as a command
+ and this terminal session will exit when the command exits
+ :param env_vars: Environment variables that will be accessible inside of the terminal
+ :param timeout: Specify the duration, in seconds to give the method to finish its execution before it times out (default is 60 seconds). If set to None, the method will continue to wait until it completes, regardless of time
+
+ :return: Terminal session
+ """
+ return self._loop.run_until_complete(
+ super().start(
+ on_data,
+ cols,
+ rows,
+ cwd,
+ terminal_id,
+ on_exit,
+ cmd,
+ env_vars,
+ timeout,
+ )
+ )
diff --git a/packages/python-sdk/tests/test_sync.py b/packages/python-sdk/tests/test_sync.py
new file mode 100644
index 000000000..f0289aff0
--- /dev/null
+++ b/packages/python-sdk/tests/test_sync.py
@@ -0,0 +1,134 @@
+import asyncio
+from unittest.mock import MagicMock
+
+from e2b import SyncSession
+
+
+def test_process_on_stdout_stderr():
+ session = SyncSession.create("Nodejs")
+
+ stdout = []
+ stderr = []
+
+ proc = session.process.start(
+ "pwd",
+ on_stdout=lambda data: stdout.append(data),
+ on_stderr=lambda data: stderr.append(data),
+ cwd="/tmp",
+ )
+
+ output = proc.wait()
+
+ assert not output.error
+ assert output.stdout == "/tmp"
+ assert output.stderr == ""
+ assert list(map(lambda message: message.line, stdout)) == ["/tmp"]
+ assert stderr == []
+
+ session.close()
+
+
+def test_process_on_exit():
+ session = SyncSession.create("Nodejs")
+
+ on_exit = MagicMock()
+
+ proc = session.process.start(
+ "pwd",
+ on_exit=lambda: on_exit(),
+ )
+
+ proc.wait()
+ on_exit.assert_called_once()
+
+ session.close()
+
+
+def test_process_send_stdin():
+ session = SyncSession.create("Nodejs")
+
+ proc = session.process.start(
+ 'read -r line; echo "$line"',
+ cwd="/code",
+ )
+ proc.send_stdin("ping\n")
+ proc.wait()
+
+ assert proc.output.stdout == "ping"
+
+ assert len(proc.output_messages) == 1
+ message = proc.output_messages[0]
+ assert message.line == "ping"
+ assert not message.error
+
+ session.close()
+
+
+def test_list_files():
+ session = SyncSession.create("Nodejs")
+ session.filesystem.make_dir("/test/new")
+
+ ls = session.filesystem.list("/test")
+ assert ["new"] == [x.name for x in ls]
+
+ session.close()
+
+
+def test_create_file():
+ session = SyncSession.create("Nodejs")
+ session.filesystem.make_dir("/test")
+ session.filesystem.write("/test/test.txt", "Hello World!")
+
+ ls = session.filesystem.list("/test")
+ assert ["test.txt"] == [x.name for x in ls]
+
+ session.close()
+
+
+def test_read_and_write():
+ session = SyncSession.create("Nodejs")
+
+ session.filesystem.write("/tmp/test.txt", "Hello World!")
+
+ content = session.filesystem.read("/tmp/test.txt")
+ assert content == "Hello World!"
+
+ session.close()
+
+
+def test_list_delete_files():
+ session = SyncSession.create("Nodejs")
+ session.filesystem.make_dir("/test/new")
+
+ ls = session.filesystem.list("/test")
+ assert ["new"] == [x.name for x in ls]
+
+ session.filesystem.remove("/test/new")
+
+ ls = session.filesystem.list("/test")
+ assert [] == [x.name for x in ls]
+
+ session.close()
+
+
+def test_watch_dir():
+ session = SyncSession.create("Nodejs")
+ session.filesystem.write("/tmp/test.txt", "Hello")
+
+ watcher = session.filesystem.watch_dir("/tmp")
+
+ events = []
+ watcher.add_event_listener(lambda e: events.append(e))
+
+ watcher.start()
+ session.filesystem.write("/tmp/test.txt", "World!")
+ session._loop.run_until_complete(asyncio.sleep(1))
+ watcher.stop()
+
+ assert len(events) >= 1
+
+ event = events[0]
+ assert event["operation"] == "Write"
+ assert event["path"] == "/tmp/test.txt"
+
+ session.close()