> ## Documentation Index
> Fetch the complete documentation index at: https://docs.orgo.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Execute Python

> Run a Python snippet on the computer and capture its output.

Runs Python code on the computer and returns its output. Each call is a fresh interpreter, so nothing carries over between requests. On Linux the code runs with `python3 -c`, `HOME=/root`, `DISPLAY=:99`, and `PATH=/usr/local/bin:/usr/bin:/bin`.

On Windows, the code is written to a temporary file and run with `C:\Python312\python.exe` from the user's Desktop folder. The response carries `stdout`, `stderr`, `exit_code`, and `output` instead of the fields listed under [Response](#response), plus `error` when the code could not run. Code that runs out of time returns `200` with `exit_code: 124` and `error: "timeout"`.

## Path parameters

<ParamField path="id" type="string" required>
  Computer ID (UUID).
</ParamField>

## Body parameters

<ParamField body="code" type="string" required>
  Python code to run. Missing, empty, or not a string returns `400`.
</ParamField>

<ParamField body="timeout" type="integer" default="10">
  How long the code may run, in seconds. Optional, and always clamped to 1-300:
  a larger value silently becomes 300, and `0` or a non-numeric value becomes
  10\. Out-of-range values are never rejected.
</ParamField>

<Note>
  `exec` takes no `?screen=` parameter. Unlike the pointer and keyboard actions,
  sending one here is silently ignored rather than rejected. The code always runs
  against the computer's default display.
</Note>

## Response

<ResponseField name="success" type="boolean">
  `true` only when the interpreter exited zero. Code that raises returns `200`
  with `success: false`, not an error status.
</ResponseField>

<ResponseField name="action" type="string">
  Always `exec`.
</ResponseField>

<ResponseField name="output" type="string">
  Combined stdout and stderr, in that order, joined by a newline when both are
  non-empty. An uncaught exception's traceback arrives here, and it is the only
  place it appears.
</ResponseField>

<ResponseField name="timeout" type="boolean">
  Always `false`. Code killed by the timeout also returns `false`, so this field
  carries no information. Infer a timeout from `success: false` with truncated
  output instead.
</ResponseField>

<ResponseField name="error" type="string | null">
  Always `null` on a `200`, including when the code raises. Read `output` for
  the traceback.
</ResponseField>

<ResponseField name="error_type" type="string | null">
  Always `null` on a `200`. It never carries a Python exception class. Parse
  `output` if you need the exception name.
</ResponseField>

## Example

<CodeGroup>
  ```bash cURL theme={null}
  curl -X POST https://www.orgo.ai/api/computers/$COMPUTER_ID/exec \
    -H "Authorization: Bearer $ORGO_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{
      "code": "import os\nprint(os.getcwd())",
      "timeout": 10
    }'
  ```

  ```python Python theme={null}
  import requests

  response = requests.post(
      f"https://www.orgo.ai/api/computers/{computer_id}/exec",
      headers={"Authorization": f"Bearer {api_key}", "Content-Type": "application/json"},
      json={
          "code": "import os\nprint(os.getcwd())",
          "timeout": 10
      }
  )

  result = response.json()
  # `output` carries the traceback on failure; `error` is always null here.
  print(result["output"])
  if not result["success"]:
      print("Script exited non-zero")
  ```

  ```javascript JavaScript theme={null}
  const response = await fetch(`https://www.orgo.ai/api/computers/${computerId}/exec`, {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${apiKey}`,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      code: 'import os\nprint(os.getcwd())',
      timeout: 10
    })
  });

  const result = await response.json();
  // `output` carries the traceback on failure; `error` is always null here.
  console.log(result.output);
  if (!result.success) {
    console.error('Script exited non-zero');
  }
  ```
</CodeGroup>

### Successful response

```json theme={null}
{
  "success": true,
  "action": "exec",
  "output": "/home/user\n",
  "timeout": false,
  "error": null,
  "error_type": null
}
```

### Response when the code raises

Still a `200`. The exception is in `output`; `error` and `error_type` stay `null`.

```json theme={null}
{
  "success": false,
  "action": "exec",
  "output": "Traceback (most recent call last):\n  File \"<string>\", line 1, in <module>\nNameError: name 'undefined_var' is not defined\n",
  "timeout": false,
  "error": null,
  "error_type": null
}
```

<Tip>
  For shell commands, use [Execute bash](/api-reference/computers/bash) instead.
</Tip>

## Errors

| Status | Meaning |
| - | - |
| `400` | `code` is missing, empty, or not a string: `{"error": "Code is required and must be a string"}`. Also returned when the computer has no VM attached: `{"error": "Desktop instance not available"}`. |
| `401` | Invalid API key: `{"error": "Invalid API key"}`. A request with no `Authorization` header returns `{"error": "Authentication required"}`. Access failures also return `401` on this endpoint, not `403`: `{"error": "You do not have access to this workspace."}` when you are neither the owner nor a member of the computer's workspace, `{"error": "This workspace is view-only. Ask the owner for write access (workspace_read_only)."}` for a view-only member, and `{"error": "This API key cannot access this workspace (workspace_scope_mismatch)."}` for a workspace-scoped key used outside its workspace. A server-side fault while verifying the credential also returns `401`, with `{"error": "Service temporarily unavailable. The database is not accepting requests. Retry shortly."}`. Retry that one; the key is fine. |
| `402` | The computer is a trial computer whose trial is not active: `{"error": "Choose a plan to continue."}`. |
| `404` | No computer with this id: `{"error": "Desktop not found"}`, plus a `hint` explaining that computer ids do not survive a rebuild. |
| `500` | The interpreter could not be started at all (with `upstream_status: 500`), or the request body is not valid JSON (with the parser's message in `error`). |
| `501` | The computer is an iPhone, or a Mac whose agent has no `/exec`: `{"error": "…", "code": "EXEC_UNSUPPORTED_ON_DEVICE"}`. On a Mac, `error` says how to run the code through [Execute bash](/api-reference/computers/bash) instead. |
| `503` | The computer could not be reached. The body is `{"error": "Could not reach the desktop. Try again in a moment."}` with a `code` and a diagnostic: `vm_status`, `desired_status`, `host_reachable`, `desktop_api_reachable`, and a `hint`. Safe to retry. Also returned when the computer never finished provisioning: `{"error": "Computer not ready"}`. |
| `504` | The call outlived the time the API hop allows: `{"error": "The command exceeded the allowed time and was aborted.", "code": "timeout"}`. No output comes back. |

Code that raises is **not** an error status: it is a `200` with
`success: false`. Every failure raised after the request leaves the API layer
carries a `request_id`. Quote it in support requests. When the computer agent
itself answered non-2xx, the body additionally carries `upstream_status`.

```json theme={null}
{
  "error": "Code is required and must be a string"
}
```


## OpenAPI

````yaml POST /computers/{id}/exec
openapi: 3.1.0
info:
  title: Orgo API
  description: >-
    Launch cloud computers that AI agents can control and interact with. Create
    workspaces, provision computers, and control them programmatically.
  version: 2.0.0
  contact:
    name: Orgo Support
    email: spencer@orgo.ai
    url: https://orgo.ai
servers:
  - url: https://www.orgo.ai/api
    description: Production
security:
  - bearerAuth: []
tags:
  - name: Account
    description: >-
      Account capacity: how many computers an account may run, and adding or
      giving back more.
  - name: Clients
    description: >-
      Run Orgo for your clients from your own app: a workspace and scoped key
      each, billed to you or to them.
  - name: Workspaces
    description: Organize computers into named workspaces
  - name: Computers
    description: Provision and manage virtual computers
  - name: Computer Lifecycle
    description: Start, stop, and restart computers
  - name: Computer Actions
    description: Control mouse, keyboard, and execute commands
  - name: Screens
    description: >-
      More than one desktop on a single computer. Each screen is its own X
      server with its own cursor and window manager, so an agent working on one
      cannot disturb another.
  - name: Files
    description: Upload and download files
  - name: Templates
    description: Author, build, and launch reproducible computers from templates
paths:
  /computers/{id}/exec:
    post:
      tags:
        - Computer Actions
      summary: Execute Python
      description: >-
        Runs Python code on the computer in a fresh interpreter and returns its
        output. On Linux the code runs with `python3 -c`. On Windows it is
        written to a temporary file and run with `C:\Python312\python.exe`, and
        the response carries `stdout`, `stderr`, `exit_code`, and `output`
        instead, plus `error` when the code could not run; code that runs out of
        time returns `200` with `exit_code` `124` and `error` `"timeout"`. An
        iPhone, or a Mac whose agent has no `/exec`, answers `501`.
      operationId: executePython
      parameters:
        - name: id
          in: path
          required: true
          description: Computer ID
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/ExecRequest'
            example:
              code: |-
                import os
                print(os.getcwd())
              timeout: 10
      responses:
        '200':
          description: >-
            The code ran. Code that raises is still a `200`, with `success:
            false` and the traceback in `output`.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ExecResponse'
              example:
                success: true
                action: exec
                output: |
                  /home/user
                timeout: false
                error: null
                error_type: null
        '400':
          description: >-
            `code` is missing, empty, or not a string, or the computer has no VM
            attached.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
              examples:
                no-code:
                  summary: No code
                  value:
                    error: Code is required and must be a string
                no-instance:
                  summary: The computer has no VM attached. Start it first.
                  value:
                    error: Desktop instance not available
        '401':
          $ref: '#/components/responses/UnauthorizedWithAccess'
        '402':
          $ref: '#/components/responses/TrialInactive'
        '404':
          description: >-
            No computer with this id. The body carries a `hint` explaining that
            computer ids do not survive a rebuild.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
              example:
                error: Desktop not found
                hint: >-
                  This id isn't on your account. Computer ids are not stable
                  across rebuilds. If the VM was recreated, re-fetch the current
                  one from GET /api/computers.
        '500':
          description: >-
            The interpreter could not be started at all (with `upstream_status:
            500`), or the body is not valid JSON (with the parser's message in
            `error`).
          content:
            application/json:
              schema:
                anyOf:
                  - $ref: '#/components/schemas/UpstreamError'
                  - $ref: '#/components/schemas/InternalError'
              example:
                error: …
                request_id: 7c1e0f4a-9b2d-4a51-8f0c-2d6b1e93a4c7
                upstream_status: 500
        '501':
          description: >-
            The computer is an iPhone, or a Mac whose agent has no `/exec`. On a
            Mac, `error` says how to run the code through `POST
            /computers/{id}/bash` instead.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
              examples:
                mac:
                  summary: A Mac whose agent has no exec
                  value:
                    error: >-
                      Exec isn't available on this computer's agent yet. Until
                      it is updated, use /bash; on a Mac call
                      /opt/homebrew/bin/python3 with the code on a quoted
                      heredoc. Never a bare python3.
                    code: EXEC_UNSUPPORTED_ON_DEVICE
                iphone:
                  summary: An iPhone
                  value:
                    error: Exec isn't available on an iPhone.
                    code: EXEC_UNSUPPORTED_ON_DEVICE
        '503':
          description: >-
            The computer could not be reached. It may be resuming, or its host
            may be unhealthy. Retry in a moment. The body carries a diagnostic:
            `vm_status`, `desired_status`, `host_reachable`,
            `desktop_api_reachable`, and a `hint`. Also returned, without the
            diagnostic, when the computer never finished provisioning.
          content:
            application/json:
              schema:
                anyOf:
                  - $ref: '#/components/schemas/UnreachableError'
                  - $ref: '#/components/schemas/InternalError'
              examples:
                unreachable:
                  summary: Unreachable
                  value:
                    error: Could not reach the desktop. Try again in a moment.
                    request_id: 7c1e0f4a-9b2d-4a51-8f0c-2d6b1e93a4c7
                    code: ECONNREFUSED
                not-ready:
                  summary: The computer never finished provisioning
                  value:
                    error: Computer not ready
                    request_id: 7c1e0f4a-9b2d-4a51-8f0c-2d6b1e93a4c7
        '504':
          $ref: '#/components/responses/CommandTimeout'
components:
  schemas:
    ExecRequest:
      type: object
      required:
        - code
      properties:
        code:
          type: string
          description: Python code to execute
        timeout:
          type: integer
          default: 10
          description: >-
            How long the code may run, in seconds. Always clamped to 1-300: a
            larger value becomes 300, and `0` or a non-numeric value becomes 10.
            Out-of-range values are never rejected.
          minimum: 1
          maximum: 300
    ExecResponse:
      type: object
      properties:
        success:
          type: boolean
          description: >-
            `true` only when the interpreter exited zero. Code that raises
            returns `200` with `success: false`.
        action:
          type: string
          enum:
            - exec
        output:
          type: string
          description: >-
            Combined stdout and stderr. An uncaught exception's traceback
            arrives here.
        timeout:
          type: boolean
          enum:
            - false
          description: >-
            Always `false`, even when the code was killed by the timeout. Infer
            a timeout from `success: false` with truncated output.
        error:
          type: 'null'
          description: Always `null` on a `200`, including when the code raises.
        error_type:
          type: 'null'
          description: Always `null` on a `200`. It never carries a Python exception class.
    Error:
      type: object
      description: >-
        The base error body. Every failure carries `error`; individual endpoints
        add the fields named in the schemas below.
      required:
        - error
      properties:
        error:
          type: string
          description: Human-readable message.
          example: Access denied
        code:
          type: string
          description: >-
            Machine-readable reason. Present on the failures that define one,
            absent otherwise.
    UpstreamError:
      type: object
      description: >-
        A failure the computer itself returned, relayed with the computer's own
        status.
      required:
        - error
        - request_id
        - upstream_status
      properties:
        error:
          type: string
          description: The message the computer returned.
        request_id:
          type: string
          description: >-
            Correlation id for this failure. The server logged the failure under
            it, so quote it in a support report.
          example: 7c1e0f4a-9b2d-4a51-8f0c-2d6b1e93a4c7
        upstream_status:
          type: integer
          description: >-
            The status the computer returned. Mirrors the status of this
            response.
          example: 409
    InternalError:
      type: object
      description: >-
        An unexpected failure. Retrying is reasonable; if it persists, quote
        `request_id`.
      required:
        - error
      properties:
        error:
          type: string
        request_id:
          type: string
          description: >-
            Present on failures raised by a route that talks to a computer.
            Absent on the others.
          example: 7c1e0f4a-9b2d-4a51-8f0c-2d6b1e93a4c7
    UnreachableError:
      type: object
      description: >-
        The computer could not be reached. The diagnostic fields, present on the
        command endpoints, say how far the request got.
      required:
        - error
        - request_id
        - code
      properties:
        error:
          type: string
          example: Could not reach the desktop. Try again in a moment.
        request_id:
          type: string
          example: 7c1e0f4a-9b2d-4a51-8f0c-2d6b1e93a4c7
        code:
          type: string
          description: >-
            The socket-level error code, or `network_error` when none was
            reported.
          example: ECONNREFUSED
        vm_status:
          type:
            - string
            - 'null'
          description: The computer's recorded status when the request failed.
        desired_status:
          type:
            - string
            - 'null'
          description: >-
            The status the computer was being driven towards, when one was
            recorded.
        host_reachable:
          type:
            - boolean
            - 'null'
          description: Whether the host running the computer answered.
        desktop_api_reachable:
          type:
            - boolean
            - 'null'
          description: Whether the computer's own API answered.
        hint:
          type: string
          description: What to do next, given the two reachability results.
    TimeoutError:
      type: object
      description: >-
        The command ran past the time allowed for it and was aborted. Raise
        `timeout` on the request, up to 300 seconds.
      required:
        - error
        - request_id
        - code
      properties:
        error:
          type: string
          example: The command exceeded the allowed time and was aborted.
        request_id:
          type: string
          example: 7c1e0f4a-9b2d-4a51-8f0c-2d6b1e93a4c7
        code:
          type: string
          enum:
            - timeout
  responses:
    UnauthorizedWithAccess:
      description: >-
        No usable credential, or an access check failed. This endpoint runs its
        workspace access checks during authentication, so it answers a missing
        membership, view-only access, or a key scoped to another workspace with
        `401`, not `403`. A server-side fault while verifying the credential
        also returns `401`, with a `Service temporarily unavailable` message.
        Retry that one; the key is fine.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'
          examples:
            invalid-key:
              summary: The key is not one of yours
              value:
                error: Invalid API key
            no-credential:
              summary: No key and no session
              value:
                error: Authentication required
            no-access:
              summary: Not the owner or a member of the workspace
              value:
                error: You do not have access to this workspace.
            view-only:
              summary: View-only member, and the request changes something
              value:
                error: >-
                  This workspace is view-only. Ask the owner for write access
                  (workspace_read_only).
            scope-mismatch:
              summary: The API key is scoped to another workspace
              value:
                error: >-
                  This API key cannot access this workspace
                  (workspace_scope_mismatch).
            service-unavailable:
              summary: Server-side fault while verifying the credential. Retry.
              value:
                error: >-
                  Service temporarily unavailable. The database is not accepting
                  requests. Retry shortly.
    TrialInactive:
      description: >-
        The computer is a free trial computer whose trial is no longer active,
        or it is paid for by its own subscription or dedicated purchase and that
        payment has lapsed.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'
          examples:
            trial:
              summary: Trial no longer active
              value:
                error: Choose a plan to continue.
            payment:
              summary: The computer's own payment has lapsed
              value:
                error: Manage this computer’s payment in Account → Usage.
    CommandTimeout:
      description: >-
        The command ran past the time allowed for it and was aborted. Nothing is
        rolled back: whatever the command did before the abort has happened.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/TimeoutError'
          example:
            error: The command exceeded the allowed time and was aborted.
            request_id: 7c1e0f4a-9b2d-4a51-8f0c-2d6b1e93a4c7
            code: timeout
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      description: API key authentication. Get your key at orgo.ai/workspaces

````

This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.