---
title: Sandboxed Python
slug: sandboxed-python
---

<Callout>
  A corresponding <a href="https://github.com/trycua/cua/blob/main/examples/sandboxed_functions_examples.py" target="_blank">Python example</a> is available for this documentation.
</Callout>

You can run Python functions securely inside a sandboxed virtual environment on a remote Cua Computer. This is useful for executing untrusted user code, isolating dependencies, or providing a safe environment for automation tasks.

## How It Works

The `sandboxed` decorator from the Computer SDK wraps a Python function so that it is executed remotely in a specified virtual environment on the target Computer. The function and its arguments are serialized, sent to the remote, and executed in isolation. Results or errors are returned to the caller.

## Example Usage

```python
from computer import Computer
from computer.helpers import sandboxed

@sandboxed()
def read_file(location: str) -> str:
    """Read contents of a file"""
    with open(location, 'r') as f:
        return f.read()

async def main():
    async with Computer(os_type="linux", provider_type="cloud", name="my-sandbox", api_key="...") as computer:
        # Call the sandboxed function (runs remotely)
        result = await read_file("/etc/hostname")
        print(result)
```

## Installing Python Packages

You can specify the virtual environment name and target computer:

```python
@sandboxed(venv_name="myenv", computer=my_computer, max_retries=5)
def my_function(...):
    ...
```

You can also install packages in the virtual environment using the `venv_install` method:

```python
await my_computer.venv_install("myenv", ["requests"])
```

## Example: Interacting with macOS Applications

You can use sandboxed functions to interact with macOS applications on a local Cua Computer (requires `os_type="darwin"`). This is particularly useful for automation tasks that involve GUI applications.

```python
# Example: Use sandboxed functions to execute code in a Cua Sandbox
from computer.helpers import sandboxed

await computer.venv_install("demo_venv", ["macos-pyxa"]) # Install packages in a virtual environment

@sandboxed("demo_venv")
def greet_and_print(name):
    """Get the HTML of the current Safari tab"""
    import PyXA
    safari = PyXA.Application("Safari")
    html = safari.current_document.source()
    print(f"Hello from inside the sandbox, {name}!")
    return {"greeted": name, "safari_html": html}

# When a @sandboxed function is called, it will execute in the sandbox
result = await greet_and_print("Cua")
# Result: {"greeted": "Cua", "safari_html": "<html>...</html>"}
# stdout and stderr are also captured and printed / raised
print("Result from sandboxed function:", result)
```

## Error Handling

If the remote execution fails, the decorator will retry up to `max_retries` times. If all attempts fail, the last exception is raised locally.
