### Create and Manage Sandbox Instance (Python) Source: https://context7.com/ucloud/ucloud-sandbox-sdk-python/llms.txt Demonstrates how to create and manage a synchronous sandbox instance using the `Sandbox.create()` method. It covers basic creation with a context manager, custom configuration options like template, timeout, environment variables, network settings, and lifecycle management (checking status, getting info, extending timeout, and killing the sandbox). ```python from ucloud_sandbox import Sandbox # Basic sandbox creation with context manager with Sandbox.create() as sandbox: result = sandbox.commands.run("echo 'Hello, World!'") print(result.stdout) # Hello, World! # Create with custom configuration sandbox = Sandbox.create( template="base", # Template name or ID timeout=600, # Timeout in seconds (max 86400 for Pro, 3600 for Hobby) metadata={"project": "ai-agent"}, envs={"NODE_ENV": "production"}, secure=True, # Require access token allow_internet_access=True, network={ "allow_out": ["1.1.1.1", "8.8.8.0/24"], "deny_out": ["192.168.0.0/16"], "allow_public_traffic": True } ) # Check sandbox status print(f"Sandbox ID: {sandbox.sandbox_id}") print(f"Running: {sandbox.is_running()}") # Get sandbox information info = sandbox.get_info() print(f"Template: {info.template_id}") print(f"Started: {info.started_at}") print(f"Expires: {info.end_at}") # Extend timeout sandbox.set_timeout(1200) # Kill sandbox when done sandbox.kill() ``` -------------------------------- ### Install UCloud Sandbox Python SDK Source: https://context7.com/ucloud/ucloud-sandbox-sdk-python/llms.txt Installs the UCloud Sandbox Python SDK using pip. This is the first step to using the SDK for creating sandboxed environments. ```bash pip install ucloud_sandbox ``` -------------------------------- ### Build Custom Sandbox Templates with UCloud Sandbox SDK Source: https://context7.com/ucloud/ucloud-sandbox-sdk-python/llms.txt Construct custom sandbox environments using the `Template` class. This includes building from various base images (Python, Node.js, Ubuntu), copying files, running commands, setting environment variables, and specifying start commands with port or URL waiting. ```python from ucloud_sandbox import Template, wait_for_port, wait_for_url # Build from Python image template = ( Template() .from_python_image("3.11") .copy("requirements.txt", "/home/user/") .copy(["app.py", "config.py"], "/app/", mode=0o755) .run_cmd("pip install -r /home/user/requirements.txt") .set_envs({"PYTHONPATH": "/app", "DEBUG": "false"}) .set_workdir("/app") .set_start_cmd("python app.py", wait_for_port(8000)) ) # Build and deploy template build_info = Template.build( template, alias="my-python-app", cpu_count=2, memory_mb=2048 ) print(f"Template ID: {build_info.template_id}") # Build from Node.js image node_template = ( Template() .from_node_image("20") .copy("package.json", "/app/") .set_workdir("/app") .npm_install() .copy(".", "/app/") .set_start_cmd("npm start", wait_for_url("http://localhost:3000/health", 200)) ) # Build from Ubuntu with system packages ubuntu_template = ( Template() .from_ubuntu_image("24.04") .apt_install(["curl", "wget", "git", "vim"]) .pip_install(["numpy", "pandas", "scikit-learn"]) .make_dir("/app/data", mode=0o755) .set_user("root") .run_cmd("chmod -R 777 /app") ) # Build from existing template extended_template = ( Template() .from_template("my-base-template") .copy("additional_files/", "/app/") .run_cmd("pip install additional-package") ) # Build from Dockerfile dockerfile_template = Template().from_dockerfile(""" FROM python:3.11 WORKDIR /app COPY requirements.txt . RUN pip install -r requirements.txt COPY . . """) # Build from private registry private_template = Template().from_image( "myregistry.com/myimage:latest", username="user", password="password" ) # Build from UCloud UHub registry uhub_template = Template().from_uhub_registry( "uhub.service.ucloud.cn/myorg/myimage:latest", username="user@ucloud.cn", password="uhub-password" ) # Background build (non-blocking) build_info = Template.build_in_background( template, alias="my-template", cpu_count=2, memory_mb=2048 ) # Check build status status = Template.get_build_status(build_info) print(f"Status: {status.status}") # Build with logging callback def on_build_log(entry): print(f"[{entry.level}] {entry.message}") Template.build( template, alias="my-template", on_build_logs=on_build_log ) # Convert template to Dockerfile dockerfile = Template.to_dockerfile(template) print(dockerfile) # Convert template to JSON json_str = Template.to_json(template) print(json_str) ``` -------------------------------- ### Manage Sandbox Filesystem with Python Source: https://context7.com/ucloud/ucloud-sandbox-sdk-python/llms.txt This snippet demonstrates how to interact with the sandbox's file system using the `ucloud_sandbox.Sandbox` class. It covers writing files (text, binary, multiple entries), reading files (as text, bytes, or stream), checking existence, getting file info, listing directory contents, creating directories, renaming/moving files, removing files/directories, and watching directories for changes. ```python from ucloud_sandbox import Sandbox with Sandbox.create() as sandbox: # Write a file sandbox.files.write("/home/user/test.txt", "Hello, World!") # Write binary data sandbox.files.write("/home/user/binary.dat", b"\x00\x01\x02\x03") # Write multiple files at once from ucloud_sandbox.sandbox.filesystem.filesystem import WriteEntry sandbox.files.write_files([ WriteEntry(path="/home/user/file1.txt", data="Content 1"), WriteEntry(path="/home/user/file2.txt", data="Content 2"), ]) # Read file as text content = sandbox.files.read("/home/user/test.txt") print(content) # Read file as bytes data = sandbox.files.read("/home/user/binary.dat", format="bytes") # Read file as stream for chunk in sandbox.files.read("/home/user/large.txt", format="stream"): print(chunk.decode()) # Check if file exists exists = sandbox.files.exists("/home/user/test.txt") print(f"File exists: {exists}") # Get file info info = sandbox.files.get_info("/home/user/test.txt") print(f"Name: {info.name}, Size: {info.size}, Mode: {info.permissions}") # List directory contents entries = sandbox.files.list("/home/user", depth=2) for entry in entries: print(f"{entry.type}: {entry.path} ({entry.size} bytes)") # Create directory sandbox.files.make_dir("/home/user/new_dir") # Rename/move file sandbox.files.rename("/home/user/test.txt", "/home/user/renamed.txt") # Remove file or directory sandbox.files.remove("/home/user/renamed.txt") # Watch directory for changes handle = sandbox.files.watch_dir("/home/user", recursive=True) for event in handle.events(): print(f"Event: {event.type} - {event.path}") if event.type == "create": break handle.stop() ``` -------------------------------- ### Get Sandbox Information and Metrics Source: https://context7.com/ucloud/ucloud-sandbox-sdk-python/llms.txt Illustrates how to retrieve detailed information and performance metrics for a specific sandbox using its ID. Requires the `ucloud_sandbox` library and `datetime` for time-based metric queries. ```python import datetime # Get sandbox info by ID info = Sandbox.get_info("sandbox-id-here") print(f"State: {info.state}") print(f"CPU: {info.cpu_count}, Memory: {info.memory_mb}MB") # Get sandbox metrics metrics = Sandbox.get_metrics( "sandbox-id-here", start=datetime.datetime.now() - datetime.timedelta(hours=1), end=datetime.datetime.now() ) for m in metrics: print(f"CPU: {m.cpu_used_pct}%, Mem: {m.mem_used}/{m.mem_total}") ``` -------------------------------- ### Create and Manage Async Sandbox Instance (Python) Source: https://context7.com/ucloud/ucloud-sandbox-sdk-python/llms.txt Demonstrates the creation and management of an asynchronous sandbox instance using `AsyncSandbox.create()`. This is suitable for use within asyncio applications. It covers using an async context manager, manual lifecycle management, running commands asynchronously, checking status, retrieving metrics, and killing the sandbox. ```python import asyncio from ucloud_sandbox import AsyncSandbox async def main(): # Async context manager async with await AsyncSandbox.create() as sandbox: result = await sandbox.commands.run("python --version") print(result.stdout) # Manual lifecycle management sandbox = await AsyncSandbox.create( timeout=300, envs={"DEBUG": "true"} ) # Run commands asynchronously result = await sandbox.commands.run("ls -la /home/user") print(result.stdout) # Check if running is_running = await sandbox.is_running() print(f"Running: {is_running}") # Get metrics metrics = await sandbox.get_metrics() for m in metrics: print(f"CPU: {m.cpu_used_pct}%, Memory: {m.mem_used}/{m.mem_total}") await sandbox.kill() asyncio.run(main()) ``` -------------------------------- ### Async Sandbox Connection and Command Execution Source: https://context7.com/ucloud/ucloud-sandbox-sdk-python/llms.txt Demonstrates how to asynchronously create, connect to, and execute commands on a UCloud sandbox. Requires the `ucloud_sandbox` library and an active sandbox ID. ```python async def reconnect(): sandbox = await AsyncSandbox.create() sandbox_id = sandbox.sandbox_id await sandbox.beta_pause() # Reconnect same = await AsyncSandbox.connect(sandbox_id) result = await same.commands.run("whoami") print(result.stdout) ``` -------------------------------- ### Connect to and Manage Sandboxes with UCloud Sandbox SDK Source: https://context7.com/ucloud/ucloud-sandbox-sdk-python/llms.txt Create, connect to, and manage sandbox instances using the `Sandbox` and `AsyncSandbox` classes. This includes creating a new sandbox, retrieving its ID, pausing it (beta), and reconnecting to an existing sandbox from a different environment. ```python from ucloud_sandbox import Sandbox, AsyncSandbox # Create sandbox and get ID sandbox = Sandbox.create(metadata={"session": "abc123"}) sandbox_id = sandbox.sandbox_id print(f"Sandbox ID: {sandbox_id}") # Pause sandbox (beta feature) sandbox.beta_pause() # Connect from different environment same_sandbox = Sandbox.connect(sandbox_id, timeout=600) result = same_sandbox.commands.run("echo 'Reconnected!'") print(result.stdout) # Instance method connect (reconnects to self) sandbox = Sandbox.create() sandbox.beta_pause() sandbox.connect() # Resume the same sandbox ``` -------------------------------- ### Control Desktop Environment with Python SDK Source: https://context7.com/ucloud/ucloud-sandbox-sdk-python/llms.txt This snippet shows how to use the `ucloud_sandbox.desktop.Sandbox` to control a desktop environment. It covers creating a desktop sandbox instance, taking screenshots (as bytes or stream), performing mouse operations (move, click, drag, scroll, press/release), and interacting with the desktop environment programmatically. ```python from ucloud_sandbox.desktop import Sandbox # Create desktop sandbox desktop = Sandbox.create( resolution=(1920, 1080), dpi=96, timeout=600 ) # Take a screenshot screenshot_bytes = desktop.screenshot() # Returns bytearray with open("screenshot.png", "wb") as f: f.write(screenshot_bytes) # Take screenshot as stream for chunk in desktop.screenshot(format="stream"): pass # Process chunks # Mouse operations desktop.move_mouse(500, 300) desktop.left_click(100, 200) desktop.double_click(100, 200) desktop.right_click(100, 200) desktop.middle_click(100, 200) # Drag operation desktop.drag(fr=(100, 100), to=(500, 500)) # Mouse scroll desktop.scroll(direction="down", amount=3) desktop.scroll(direction="up", amount=5) # Mouse press and release (for custom interactions) desktop.mouse_press(button="left") desktop.mouse_release(button="left") ``` -------------------------------- ### List and Filter Sandboxes with Pagination Source: https://context7.com/ucloud/ucloud-sandbox-sdk-python/llms.txt Shows how to list, filter, and paginate through sandboxes using the `SandboxPaginator` and `SandboxQuery`. Supports filtering by state and metadata. Requires the `ucloud_sandbox` library. ```python from ucloud_sandbox import Sandbox, SandboxPaginator, SandboxQuery from ucloud_sandbox.api.client.models import SandboxState # List all running sandboxes paginator = SandboxPaginator( query=SandboxQuery(state=[SandboxState.RUNNING]), limit=10 ) while paginator.has_next: sandboxes = paginator.next_page() for sb in sandboxes: print(f"ID: {sb.sandbox_id}, Template: {sb.template_id}") # Filter by metadata paginator = SandboxPaginator( query=SandboxQuery( metadata={"project": "ai-agent"}, state=[SandboxState.RUNNING, SandboxState.PAUSED] ) ) ``` -------------------------------- ### Sandbox Creation API Source: https://context7.com/ucloud/ucloud-sandbox-sdk-python/llms.txt Provides methods for creating and managing synchronous sandbox instances for running commands and managing files in isolated cloud environments. ```APIDOC ## Sandbox.create ### Description Create a new sandbox instance for running commands and managing files in an isolated cloud environment. ### Method `Sandbox.create()` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python from ucloud_sandbox import Sandbox # Basic sandbox creation with context manager with Sandbox.create() as sandbox: result = sandbox.commands.run("echo 'Hello, World!'") print(result.stdout) # Hello, World! # Create with custom configuration sandbox = Sandbox.create( template="base", # Template name or ID timeout=600, # Timeout in seconds (max 86400 for Pro, 3600 for Hobby) metadata={"project": "ai-agent"}, envs={"NODE_ENV": "production"}, secure=True, # Require access token allow_internet_access=True, network={ "allow_out": ["1.1.1.1", "8.8.8.0/24"], "deny_out": ["192.168.0.0/16"], "allow_public_traffic": True } ) # Check sandbox status print(f"Sandbox ID: {sandbox.sandbox_id}") print(f"Running: {sandbox.is_running()}") # Get sandbox information info = sandbox.get_info() print(f"Template: {info.template_id}") print(f"Started: {info.started_at}") print(f"Expires: {info.end_at}") # Extend timeout sandbox.set_timeout(1200) # Kill sandbox when done sandbox.kill() ``` ### Response #### Success Response (200) - **sandbox_id** (string) - The unique identifier for the sandbox instance. - **is_running()** (method) - Returns a boolean indicating if the sandbox is currently running. - **get_info()** (method) - Returns an object containing sandbox information (template_id, started_at, end_at). - **set_timeout(seconds)** (method) - Sets a new timeout for the sandbox. - **kill()** (method) - Terminates the sandbox instance. #### Response Example ```json { "sandbox_id": "sandbox-12345abcde", "is_running": true, "info": { "template_id": "base", "started_at": "2023-10-27T10:00:00Z", "end_at": "2023-10-27T11:00:00Z" } } ``` ``` -------------------------------- ### AsyncSandbox Creation API Source: https://context7.com/ucloud/ucloud-sandbox-sdk-python/llms.txt Provides methods for creating and managing asynchronous sandbox instances for non-blocking operations within asyncio environments. ```APIDOC ## AsyncSandbox.create ### Description Create an async sandbox instance for non-blocking operations in asyncio environments. ### Method `AsyncSandbox.create()` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python import asyncio from ucloud_sandbox import AsyncSandbox async def main(): # Async context manager async with await AsyncSandbox.create() as sandbox: result = await sandbox.commands.run("python --version") print(result.stdout) # Manual lifecycle management sandbox = await AsyncSandbox.create( timeout=300, envs={"DEBUG": "true"} ) # Run commands asynchronously result = await sandbox.commands.run("ls -la /home/user") print(result.stdout) # Check if running is_running = await sandbox.is_running() print(f"Running: {is_running}") # Get metrics metrics = await sandbox.get_metrics() for m in metrics: print(f"CPU: {m.cpu_used_pct}%, Memory: {m.mem_used}/{m.mem_total}") await sandbox.kill() asyncio.run(main()) ``` ### Response #### Success Response (200) - **is_running()** (method) - Returns a boolean indicating if the sandbox is currently running. - **get_metrics()** (method) - Returns a list of metric objects for the sandbox. - **kill()** (method) - Terminates the sandbox instance. #### Response Example ```json { "is_running": true, "metrics": [ { "cpu_used_pct": 10.5, "mem_used": 512000000, "mem_total": 1073741824 } ] } ``` ``` -------------------------------- ### Desktop Automation with UCloud Sandbox SDK Source: https://context7.com/ucloud/ucloud-sandbox-sdk-python/llms.txt Control desktop elements like cursor position, screen size, keyboard input, application launching, and window management using the UCloud Sandbox SDK. It also includes VNC streaming capabilities and cleanup functions. ```python from ucloud_sandbox import desktop # Get cursor position x, y = desktop.get_cursor_position() print(f"Cursor at: ({x}, {y})") # Get screen size width, height = desktop.get_screen_size() print(f"Screen: {width}x{height}") # Keyboard - type text desktop.write("Hello, World!", chunk_size=25, delay_in_ms=75) # Keyboard - press special keys desktop.press("enter") desktop.press("tab") desktop.press("escape") # Keyboard shortcuts (modifier + key) desktop.press(["ctrl", "c"]) # Copy desktop.press(["ctrl", "v"]) # Paste desktop.press(["alt", "tab"]) # Switch window desktop.press(["ctrl", "shift", "s"]) # Save as # Wait for operations desktop.wait(1000) # Wait 1 second # Open file or URL desktop.open("https://example.com") desktop.open("/home/user/document.pdf") # Launch application desktop.launch("firefox") desktop.launch("gedit", uri="/home/user/file.txt") # Window management window_id = desktop.get_current_window_id() window_title = desktop.get_window_title(window_id) print(f"Current window: {window_title}") # Get all windows of an application firefox_windows = desktop.get_application_windows("firefox") for wid in firefox_windows: print(f"Firefox window: {desktop.get_window_title(wid)}") # VNC streaming desktop.stream.start( vnc_port=5900, port=6080, require_auth=True ) # Get VNC URL url = desktop.stream.get_url( auto_connect=True, view_only=False, resize="scale" ) print(f"VNC URL: {url}") # Get auth key if authentication is enabled auth_key = desktop.stream.get_auth_key() print(f"Auth key: {auth_key}") # Stop streaming desktop.stream.stop() # Clean up desktop.kill() ``` -------------------------------- ### Execute Shell Commands in Sandbox (Python) Source: https://context7.com/ucloud/ucloud-sandbox-sdk-python/llms.txt Details how to execute shell commands within a sandbox environment using `sandbox.commands.run()`. This includes simple command execution, running commands with custom environment variables and working directories, handling streaming output via callbacks, executing commands in the background, listing running processes, and killing specific processes. ```python from ucloud_sandbox import Sandbox with Sandbox.create() as sandbox: # Simple command execution result = sandbox.commands.run("echo 'Hello'") print(f"stdout: {result.stdout}") print(f"stderr: {result.stderr}") print(f"exit_code: {result.exit_code}") # Command with environment variables result = sandbox.commands.run( "echo $MY_VAR", envs={"MY_VAR": "custom_value"}, cwd="/home/user", timeout=30 ) # Streaming output with callbacks def on_stdout(line): print(f"[OUT] {line}") def on_stderr(line): print(f"[ERR] {line}") result = sandbox.commands.run( "for i in 1 2 3; do echo $i; sleep 1; done", on_stdout=on_stdout, on_stderr=on_stderr, timeout=60 ) # Background command execution handle = sandbox.commands.run( "python -m http.server 8000", background=True, timeout=0 # No timeout for background ) print(f"Background PID: {handle.pid}") # List running processes processes = sandbox.commands.list() for proc in processes: print(f"PID: {proc.pid}, Command: {proc.cmd}") # Kill a specific process sandbox.commands.kill(handle.pid) ``` -------------------------------- ### Sandbox Commands API Source: https://context7.com/ucloud/ucloud-sandbox-sdk-python/llms.txt Allows execution of shell commands within a sandbox environment, with options for streaming output, setting timeouts, and managing processes. ```APIDOC ## sandbox.commands.run ### Description Execute shell commands in the sandbox with streaming output and timeout control. ### Method `sandbox.commands.run(command, **kwargs)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python from ucloud_sandbox import Sandbox with Sandbox.create() as sandbox: # Simple command execution result = sandbox.commands.run("echo 'Hello'") print(f"stdout: {result.stdout}") print(f"stderr: {result.stderr}") print(f"exit_code: {result.exit_code}") # Command with environment variables result = sandbox.commands.run( "echo $MY_VAR", envs={"MY_VAR": "custom_value"}, cwd="/home/user", timeout=30 ) # Streaming output with callbacks def on_stdout(line): print(f"[OUT] {line}") def on_stderr(line): print(f"[ERR] {line}") result = sandbox.commands.run( "for i in 1 2 3; do echo $i; sleep 1; done", on_stdout=on_stdout, on_stderr=on_stderr, timeout=60 ) # Background command execution handle = sandbox.commands.run( "python -m http.server 8000", background=True, timeout=0 # No timeout for background ) print(f"Background PID: {handle.pid}") # List running processes processes = sandbox.commands.list() for proc in processes: print(f"PID: {proc.pid}, Command: {proc.cmd}") # Kill a specific process sandbox.commands.kill(handle.pid) ``` ### Response #### Success Response (200) - **stdout** (string) - Standard output of the command. - **stderr** (string) - Standard error of the command. - **exit_code** (integer) - The exit code of the command. - **pid** (integer) - The process ID (for background commands). - **cmd** (string) - The command executed (for listed processes). #### Response Example ```json { "stdout": "Hello\n", "stderr": "", "exit_code": 0 } ``` ``` -------------------------------- ### Execute Python Code with State using Code Interpreter Source: https://context7.com/ucloud/ucloud-sandbox-sdk-python/llms.txt This snippet demonstrates the `ucloud_sandbox.code_interpreter.Sandbox` for executing Python code. It highlights basic execution, stateful execution where variables persist across runs, retrieving results and logs, error handling, streaming output with callbacks, creating and managing custom execution contexts, and handling rich output like charts and images. ```python from ucloud_sandbox.code_interpreter import Sandbox with Sandbox.create() as sandbox: # Basic code execution execution = sandbox.run_code("print('Hello, World!')") print(execution.logs.stdout) # ['Hello, World!'] # Stateful execution - variables persist sandbox.run_code("x = 10") sandbox.run_code("y = 20") execution = sandbox.run_code("print(x + y)") print(execution.logs.stdout) # ['30'] # Get execution results execution = sandbox.run_code("1 + 1") print(execution.text) # '2' print(execution.results) # List of Result objects # Handle errors execution = sandbox.run_code("1/0") if execution.error: print(f"Error: {execution.error.name} - {execution.error.value}") print(execution.error.traceback) # Streaming output with callbacks def on_stdout(msg): print(f"[stdout] {msg.line}") def on_result(result): print(f"[result] {result.text}") execution = sandbox.run_code( "for i in range(5): print(i)", on_stdout=on_stdout, on_result=on_result, timeout=30 ) # Create custom execution context ctx = sandbox.create_code_context(cwd="/home/user/project") execution = sandbox.run_code("import os; print(os.getcwd())", context=ctx) # List all contexts contexts = sandbox.list_code_contexts() for c in contexts: print(f"Context: {c.id}, Language: {c.language}") # Restart a context (clear variables) sandbox.restart_code_context(ctx) # Remove a context sandbox.remove_code_context(ctx) # Rich output - charts, images, HTML execution = sandbox.run_code(""" import matplotlib.pyplot as plt plt.plot([1, 2, 3], [1, 4, 9]) plt.show() """) for result in execution.results: if result.png: print(f"Got PNG image: {len(result.png)} bytes") if result.chart: print(f"Got chart: {result.chart.type}") ``` -------------------------------- ### Set UCloud Sandbox API Key Environment Variable Source: https://context7.com/ucloud/ucloud-sandbox-sdk-python/llms.txt Sets the UCLOUD_SANDBOX_API_KEY environment variable, which is required for authenticating with the UCloud Sandbox service. Ensure you replace 'your_api_key' with your actual API key. ```bash export UCLOUD_SANDBOX_API_KEY=your_api_key ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.