{"id":45777912,"url":"https://github.com/datalayer/code-sandboxes","last_synced_at":"2026-02-26T10:45:14.426Z","repository":{"id":333891847,"uuid":"1109930565","full_name":"datalayer/code-sandboxes","owner":"datalayer","description":"{ } Code Sandboxes.","archived":false,"fork":false,"pushed_at":"2026-02-14T19:16:36.000Z","size":773,"stargazers_count":3,"open_issues_count":1,"forks_count":0,"subscribers_count":0,"default_branch":"main","last_synced_at":"2026-02-15T01:35:19.673Z","etag":null,"topics":["code","sandbox"],"latest_commit_sha":null,"homepage":"https://code-sandboxes.datalayer.tech","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"bsd-3-clause","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/datalayer.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null},"funding":{"github":["datalayer"]}},"created_at":"2025-12-04T13:35:22.000Z","updated_at":"2026-02-11T06:39:58.000Z","dependencies_parsed_at":null,"dependency_job_id":null,"html_url":"https://github.com/datalayer/code-sandboxes","commit_stats":null,"previous_names":["datalayer/code-sandboxes"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/datalayer/code-sandboxes","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/datalayer%2Fcode-sandboxes","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/datalayer%2Fcode-sandboxes/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/datalayer%2Fcode-sandboxes/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/datalayer%2Fcode-sandboxes/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/datalayer","download_url":"https://codeload.github.com/datalayer/code-sandboxes/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/datalayer%2Fcode-sandboxes/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":29856746,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-02-26T08:51:08.701Z","status":"ssl_error","status_checked_at":"2026-02-26T08:50:19.607Z","response_time":89,"last_error":"SSL_read: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["code","sandbox"],"created_at":"2026-02-26T10:45:12.129Z","updated_at":"2026-02-26T10:45:14.421Z","avatar_url":"https://github.com/datalayer.png","language":"Python","readme":"\u003c!--\n  ~ Copyright (c) 2025-2026 Datalayer, Inc.\n  ~\n  ~ BSD 3-Clause License\n--\u003e\n\n[![Datalayer](https://assets.datalayer.tech/datalayer-25.svg)](https://datalayer.io)\n\n[![Become a Sponsor](https://img.shields.io/static/v1?label=Become%20a%20Sponsor\u0026message=%E2%9D%A4\u0026logo=GitHub\u0026style=flat\u0026color=1ABC9C)](https://github.com/sponsors/datalayer)\n\n# { } Code Sandboxes\n\n[![PyPI - Version](https://img.shields.io/pypi/v/code-sandboxes)](https://pypi.org/project/code-sandboxes)\n\nCode Sandboxes `code_sandboxes` is a Python package for safe, isolated environments where an AI system can write, run, and test code without affecting the real world or the user's device.\n\nThis package provides a unified API for code execution with features like:\n\n- **Code Execution**: Execute Python code with streaming output and rich results\n- **Filesystem Operations**: Read, write, list, upload, and download files\n- **Command Execution**: Run shell commands with streaming support\n- **Context Management**: Maintain state across multiple executions\n- **Snapshots**: Save and restore sandbox state (Datalayer runtime)\n- **GPU Support**: Access GPU compute for ML workloads (Datalayer runtime)\n\n## Sandbox Variants\n\nFour variants are available:\n\n| Variant | Isolation | Use Case |\n|---------|-----------|----------|\n| `local-eval` | None (Python exec) | Development, testing |\n| `local-docker` | Container (Jupyter Server) | Local isolated execution |\n| `local-jupyter` | Process (Jupyter kernel) | Local persistent state |\n| `datalayer-runtime` | Cloud VM | Production, GPU workloads |\n\n## Installation\n\n```bash\n# Basic installation\npip install code-sandboxes\n\n# With Datalayer runtime support\npip install code-sandboxes[datalayer]\n\n# With Docker support\npip install code-sandboxes[docker]\n\n# All features\npip install code-sandboxes[all]\n```\n\n### Docker Variant Setup\n\nThe `local-docker` variant runs a Jupyter Server inside a Docker container and uses\n`jupyter-kernel-client` to execute code.\n\nBuild the Docker image used by `LocalDockerSandbox`:\n\n```bash\ndocker build -t code-sandboxes-jupyter:latest -f docker/Dockerfile .\n```\n\n## Quick Start\n\n### Simple Code Execution\n\n```python\nfrom code_sandboxes import Sandbox\n\n# Create a sandbox with timeout\nwith Sandbox.create(variant=\"local-eval\", timeout=60) as sandbox:\n    # Execute code\n    result = sandbox.run_code(\"x = 1 + 1\")\n    result = sandbox.run_code(\"print(x)\")  # prints 2\n\n    # Multi-statement blocks return the last expression\n    result = sandbox.run_code(\"\"\"\nx = 10\nx * 2\n\"\"\")\n    print(result.text)  # \"20\"\n    \n    # Access results\n    print(result.stdout)  # \"2\"\n```\n\n### Cloud Execution with GPU\n\n```python\nfrom code_sandboxes import Sandbox\n\n# Create a cloud sandbox with GPU\nwith Sandbox.create(\n    variant=\"datalayer-runtime\",\n    gpu=\"T4\",\n    environment=\"python-gpu-env\",\n    timeout=300,\n) as sandbox:\n    sandbox.run_code(\"import torch\")\n    result = sandbox.run_code(\"print(torch.cuda.is_available())\")\n```\n\n### Filesystem Operations\n\n```python\nwith Sandbox.create() as sandbox:\n    # Write files\n    sandbox.files.write(\"/data/test.txt\", \"Hello World\")\n    \n    # Read files\n    content = sandbox.files.read(\"/data/test.txt\")\n    \n    # List directory\n    for f in sandbox.files.list(\"/data\"):\n        print(f.name, f.size)\n    \n    # Upload/download\n    sandbox.files.upload(\"local_file.txt\", \"/remote/file.txt\")\n    sandbox.files.download(\"/remote/file.txt\", \"downloaded.txt\")\n```\n\n### Command Execution\n\n```python\nwith Sandbox.create() as sandbox:\n    # Run a command and wait for completion\n    result = sandbox.commands.run(\"ls -la\")\n    print(result.stdout)\n    \n    # Execute with streaming output\n    process = sandbox.commands.exec(\"python\", \"-c\", \"print('hello')\")\n    for line in process.stdout:\n        print(line, end=\"\")\n    \n    # Install system packages\n    sandbox.commands.install_system_packages([\"curl\", \"wget\"])\n```\n\n### Snapshots (Datalayer Runtime)\n\n```python\nwith Sandbox.create(variant=\"datalayer-runtime\") as sandbox:\n    # Set up environment\n    sandbox.install_packages([\"pandas\", \"numpy\"])\n    sandbox.run_code(\"import pandas as pd; df = pd.DataFrame({'a': [1,2,3]})\")\n    \n    # Create snapshot\n    snapshot = sandbox.create_snapshot(\"my-setup\")\n    print(f\"Snapshot created: {snapshot.id}\")\n\n# Later: restore from snapshot\nwith Sandbox.create(variant=\"datalayer-runtime\", snapshot_name=\"my-setup\") as sandbox:\n    # State is restored\n    result = sandbox.run_code(\"print(df)\")\n```\n\n### Streaming Output\n\n```python\nfrom code_sandboxes import Sandbox, OutputMessage\n\ndef handle_stdout(msg: OutputMessage):\n    print(f\"[stdout] {msg.line}\")\n\ndef handle_stderr(msg: OutputMessage):\n    print(f\"[stderr] {msg.line}\")\n\nwith Sandbox.create() as sandbox:\n    result = sandbox.run_code(\n        \"for i in range(5): print(f'Step {i}')\",\n        on_stdout=handle_stdout,\n        on_stderr=handle_stderr,\n    )\n```\n\n## API Reference\n\n### Sandbox.create()\n\nFactory method to create sandboxes:\n\n```python\nsandbox = Sandbox.create(\n    variant=\"datalayer-runtime\",  # Sandbox type\n    timeout=60,                   # Execution timeout (seconds)\n    environment=\"python-cpu-env\",  # Runtime environment\n    gpu=\"T4\",                     # GPU type (T4, A100, H100, etc.)\n    cpu=2.0,                      # CPU cores\n    memory=4096,                  # Memory in MB\n    env={\"MY_VAR\": \"value\"},      # Environment variables\n    network_policy=\"none\",        # Network access policy\n    allowed_hosts=[\"localhost\"],   # Allowlist when policy is allowlist\n    tags={\"project\": \"demo\"},     # Metadata tags\n)\n\n# Network policies:\n# - inherit: default behavior for the sandbox variant\n# - none: block all outbound connections\n# - allowlist: allow only hosts in allowed_hosts\n# - all: allow all outbound connections\n```\n\n### Execution Result\n\n```python\nresult = sandbox.run_code(\"print('hello')\")\n\nresult.success    # bool: Whether execution succeeded\nresult.stdout     # str: Standard output\nresult.stderr     # str: Standard error\nresult.text       # str: Main result text\nresult.results    # list[Result]: Rich results (HTML, images, etc.)\nresult.code_error # CodeError: Error details if failed\nresult.execution_ok     # bool: Infrastructure execution status\nresult.execution_error  # str | None: Infrastructure error details\nresult.exit_code        # int | None: Exit code if code called sys.exit()\n\n# Error handling\nif not result.execution_ok:\n    print(f\"Sandbox failed: {result.execution_error}\")\nelif result.exit_code not in (None, 0):\n    print(f\"Process exited with code: {result.exit_code}\")\nelif result.code_error:\n    print(f\"Python error: {result.code_error.name}: {result.code_error.value}\")\nelse:\n    print(result.text)\n```\n\n### Core Methods\n\n| Method | Description |\n|--------|-------------|\n| `Sandbox.create()` | Create a new sandbox |\n| `Sandbox.from_id(id)` | Reconnect to an existing sandbox |\n| `Sandbox.list()` | List all sandboxes |\n| `sandbox.run_code(code)` | Execute Python code |\n| `sandbox.files.read(path)` | Read file contents |\n| `sandbox.files.write(path, content)` | Write file contents |\n| `sandbox.files.list(path)` | List directory contents |\n| `sandbox.commands.run(cmd)` | Run shell command |\n| `sandbox.commands.exec(*args)` | Execute with streaming output |\n| `sandbox.set_timeout(seconds)` | Update timeout |\n| `sandbox.create_snapshot(name)` | Save sandbox state |\n| `sandbox.terminate()` / `sandbox.kill()` | Stop sandbox |\n\n## Configuration\n\n### Environment Variables\n\n- `DATALAYER_API_KEY`: API key for Datalayer runtime authentication\n\n### SandboxConfig\n\n```python\nfrom code_sandboxes import SandboxConfig\n\nconfig = SandboxConfig(\n    timeout=30.0,              # Default execution timeout\n    environment=\"python-cpu-env\",\n    memory_limit=4 * 1024**3,  # 4GB\n    cpu_limit=2.0,\n    gpu=\"T4\",\n    working_dir=\"/workspace\",\n    env_vars={\"DEBUG\": \"1\"},\n    max_lifetime=3600,         # 1 hour\n)\n\nsandbox = Sandbox.create(config=config)\n```\n\n## License\n\nCopyright (c) 2025-2026 Datalayer, Inc.\n\nBSD 3-Clause License\n","funding_links":["https://github.com/sponsors/datalayer"],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdatalayer%2Fcode-sandboxes","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fdatalayer%2Fcode-sandboxes","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdatalayer%2Fcode-sandboxes/lists"}