All Products
Search
Document Center

Function Compute:Code Interpreter

Last Updated:Jun 23, 2026

Code Interpreter is a secure sandbox environment that lets you run Python code, manage the file system, and execute shell commands. This topic describes the API operations for Code Interpreter.

Features

The Code Interpreter API supports the following features:

  • Code execution: Securely execute code in languages such as Python and JavaScript.

  • File management: Upload, download, move, and delete files.

  • File system operations: Create directories and query file status.

  • Context Management: An independent code execution environment

  • Session management: Manage concurrent sessions and control timeouts.

The Code Interpreter API is divided into a control plane and a data plane:

Usage notes

  • When you log on to the AgentRun console for the first time, create the AliyunServiceRoleForAgentRun service-linked role as prompted. You can then use the SDK to perform operations.

  • On the Runtimes and Sandboxes tab in the console, select Sandbox. Click Create Sandbox Template and select Code Interpreter Sandbox to create a template.

  • A sandbox template defines the basic configuration for a set of sandbox instances. A sandbox instance is the environment where code tasks are executed. The maximum lifecycle of a sandbox instance is 6 hours. You can also use the sandboxIdleTimeoutInSeconds parameter to set a timeout period. If a session is idle for longer than the specified period, the instance is terminated before the end of its 6-hour lifecycle.

Usage flow overview

  1. Create a Code Interpreter template

  2. Start a Code Interpreter sandbox instance

  3. Create an execution context

  4. Execute code

Expand to view a basic usage flow example

# 1. Create a Code Interpreter (control plane)
curl -X POST "https://agentrun.{regionid}.aliyuncs.com/2025-09-10/templates" \
  -H "Content-Type: application/json" \
  -H "X-Acs-Parent-ID: {Alibaba Cloud account ID}" \
  -d '{
    "templateName": "my-interpreter",
    "description": "A code interpreter for data analytics",
    "networkConfiguration": {
      "networkMode": "PUBLIC"
    },
    "cpu": 2,
    "memory": 4096
  }'

# 2. Start a sandbox instance (control plane)
curl -X POST "https://agentrun.{regionid}.aliyuncs.com/2025-09-10/sandboxes" \
  -H "Content-Type: application/json" \
  -H "X-Acs-Parent-ID: {Alibaba Cloud account ID}" \
  -d '{
    "sandboxId": "yourSandboxId"
  }'

# 3. Create a context (data plane)
curl -X POST "https://{accountid}.agentrun-data.{regionid}.aliyuncs.com/sandboxes/{sandboxId}/contexts" \
  -H "Content-Type: application/json" \
  -H "X-Acs-Parent-ID: {Alibaba Cloud account ID}"

# 4. Execute code (data plane)
curl -X POST "https://{accountid}.agentrun-data.{regionid}.aliyuncs.com/sandboxes/{sandboxId}/contexts/execute" \
  -H "Content-Type: application/json" \
  -H "X-Acs-Parent-ID: {Alibaba Cloud account ID}" \
  -d '{
    "contextId": "ctx-12345-67890",
    "code": "print(\"Hello, World!\")",
  }'

Control plane OpenAPI

Preparations

  1. Go to OpenAPI Explorer.

  2. On the top menu bar, click Select Product. Then, search for and select AgentRun.

  3. In the navigation pane on the left, you can find the API operations under Debug > Browser Sandbox.

Template management

For more information, see the API documentation on the OpenAPI portal.

Data plane OpenAPI

Preparations

Use the following base URL for the data plane: https://${Alibaba Cloud account ID}.agentrun-data.ap-southeast-1.aliyuncs.com/

You can click your profile picture in the upper-right corner of the product console to obtain your Alibaba Cloud account ID.

Sandbox instance management

Note

These API operations are not yet available in OpenAPI Explorer. You can use the SDK or call the API endpoints directly.

Create a sandbox instance

URI of the request: POST ${BASEURL}/sandboxes

Request header: X-Acs-Parent-Id: ${Alibaba Cloud account ID}

  • Content-Type: application/json

Request body: application/json

{
  "templateName": "string",                          // Required. The template name. The system queries the template_id based on the templateName.
  "sandboxId": "string",                             // Optional. A custom sandbox ID for end-to-end tracing. If not specified, the system automatically generates an ID in ULID format.
}

Response example:

{
  "sandboxId": "01JCED8Z9Y6XQVK8M2NRST5WXY",
  "templateId": "01JCED8Z9Y6XQVK8M2NRST5ABC",
  "templateName": "python-sandbox",
  "templateType": "CodeInterpreter",
  "status": "READY",
  "sandboxIdleTimeoutInSeconds": 3600,
  "createdAt": "2024-12-02T10:30:00Z",
  "lastUpdatedAt": "2024-12-02T10:30:15Z",
  "metadata": {
    "fcSessionDetails": {
      "sessionId": "1234567890abcdef",
      "sessionStatus": "Active",
      "sessionIdleTimeoutInSeconds": 3600,
      "functionName": "sandbox-function",
      "qualifier": "LATEST",
      "containerId": "container-123",
      "createdTime": "2024-12-02T10:30:00Z",
      "lastModifiedTime": "2024-12-02T10:30:15Z",
      "sessionAffinityType": "HEADER_FIELD"
    }
  }
}

Stop a sandbox instance

URI of the request: POST ${BASEURL}/sandboxes/{sandboxId}/stop

Request header: X-Acs-Parent-Id: ${Alibaba Cloud account ID}

Path parameters:

  • sandboxId (string, Required): The sandbox ID.

Request body: None

Example response:

{
  "sandboxId": "01JCED8Z9Y6XQVK8M2NRST5WXY",
  "templateId": "01JCED8Z9Y6XQVK8M2NRST5ABC",
  "templateName": "python-sandbox",
  "templateType": "CodeInterpreter",
  "status": "TERMINATED",
  "sandboxIdleTimeoutInSeconds": 3600,
  "createdAt": "2024-12-02T10:30:00Z",
  "lastUpdatedAt": "2024-12-02T11:00:00Z",
  "endedAt": "2024-12-02T11:00:00Z"
}

Note:

  • Stopping a sandbox deletes the FC session and updates the database status to TERMINATED.

  • This operation is idempotent. If the sandbox is already in the TERMINATED state, a response is returned immediately.

  • The endedAt timestamp is set.

Delete a sandbox instance

URI of the request: DELETE ${BASEURL}/sandboxes/{sandboxId}

Request header: X-Acs-Parent-Id: ${Alibaba Cloud account ID}

Path parameters:

  • sandboxId (string, Required): The sandbox ID.

Request body: None

Response example:

{
  "sandboxId": "01JCED8Z9Y6XQVK8M2NRST5WXY",
  "templateId": "01JCED8Z9Y6XQVK8M2NRST5ABC",
  "templateName": "python-sandbox",
  "templateType": "CodeInterpreter",
  "status": "READY|TERMINATED",
  "sandboxIdleTimeoutInSeconds": 3600,
  "createdAt": "2024-12-02T10:30:00Z",
  "lastUpdatedAt": "2024-12-02T11:30:00Z",
  "endedAt": "2024-12-02T11:00:00Z"
}

Deleting a sandbox performs the following operations:

  • Checks if the sandbox exists.

  • If the sandbox is in the READY state, it first calls StopSandbox to delete the FC session.

  • Returns the status of the sandbox before deletion.

Status descriptions

The status flow of a sandbox is as follows:

  • CREATING: The sandbox instance is being created.

  • READY: Ready to use.

  • TERMINATED: The sandbox instance has been stopped using the StopSandbox API operation.

Error responses

All API operations return errors in a unified format:

{
  "error": {
    "code": "ERROR_CODE",
    "message": "Error description"
  }
}

Common error codes:

  • 400 Bad Request: The request parameters are invalid.

  • 404 Not Found: The sandbox does not exist.

  • 500 Internal Server Error: An internal server error occurred.

Health check

Check service health status

Request syntax: GET ${BASEURL}/sandboxes/{sandboxId}/health

Request header: X-Acs-Parent-Id: ${Alibaba Cloud account ID}

Query parameters: None

Response example:

{
  "status": "ok",
  "service": "sandbox-code-interpreter",
  "version": "v1",
  "timestamp": "2025-11-15T09:45:01.068104+08:00",
  "uptime": 1142269582541
}

Context management

List all contexts

Request syntax: GET ${BASEURL}/sandboxes/{sandboxId}/contexts

Request header: X-Acs-Parent-Id: ${Alibaba Cloud account ID}

Query parameters: None

Response example:

[
  {
    "id": "kernel-12345-67890",
    "language": "python",
    "cwd": "/tmp/sandbox/home/user"
  }
]

Create a new context

Request syntax: POST ${BASEURL}/sandboxes/{sandboxId}/contexts

Request header: X-Acs-Parent-Id: ${Alibaba Cloud account ID}

  • Content-Type: application/json

Request body: application/json

{
  "language": "python",  // Required. `python` or `javascript`.
  "cwd": "/tmp/sandbox/home/user"  // Optional. The working directory.
}

Response example:

{
  "id": "271f70d5-9065-4403-8ea3-4d541f7d2bb8",
  "language": "python",
  "cwd": "/home/user"
}

Retrieve context details

Request syntax: GET ${BASEURL}/sandboxes/{sandboxId}/contexts/{contextId}

Path parameters:

  • contextId (string, Required): The unique identifier of the context.

Request header: X-Acs-Parent-Id: ${Alibaba Cloud account ID}

Query parameters: None

Response example:

{
  "id": "271f70d5-9065-4403-8ea3-4d541f7d2bb8",
  "language": "python",
  "cwd": "/home/user"
}

Delete a context

Request syntax: DELETE ${BASEURL}/sandboxes/{sandboxId}/contexts/{contextId}

Path parameters:

  • contextId (string, Required): The unique identifier of the context.

Request header: X-Acs-Parent-Id: ${Alibaba Cloud account ID}

Query parameters: None

Response: 204 No Content (no response body)

File system operations

Read file content

Request syntax: GET ${BASEURL}/sandboxes/{sandboxId}/files

Request header: X-Acs-Parent-Id: ${Alibaba Cloud account ID}

Query parameters:

  • path (string, Required): The file path. Text and binary files are supported.

Response example:

{
  "name": "example.txt",
  "type": "file",
  "path": "/workspace/example.txt",
  "size": 1024,
  "mode": 420,
  "permissions": "-rw-r--r--",
  "owner": "user",
  "group": "group",
  "modifiedTime": "2025-11-15T10:30:00Z",
  "content": "Hello, World!\nThis is a text file.",
  "encoding": "utf-8"
}

Notes:

  • Text file: encoding is "utf-8", and content is the UTF-8 text content.

  • Binary file: encoding is "base64", and content is the base64-encoded content.

Write file content

Request syntax: POST ${BASEURL}/sandboxes/{sandboxId}/files

Request header: X-Acs-Parent-Id: ${Alibaba Cloud account ID}

  • Content-Type: application/json

Request body: application/json

{
  "path": "example.txt",  // Required. The file path. Hidden files are not supported.
  "content": "Hello, World!\nThis is a text file.",  // Required. The UTF-8 text content.
  "encoding": "utf-8"  // Optional. Default is utf-8.
}

File limits:

  • Only text file name extensions such as .txt, .py, .json, and .md are supported.

  • You cannot create hidden files that start with a period (.).

  • Parent directories are created automatically if they do not exist.

  • Default file permission: 0644

{
  "path": "/home/user/example.txt",
  "size": 25
}

List directory contents

Request syntax: GET ${BASEURL}/sandboxes/{sandboxId}/filesystem

Request header: X-Acs-Parent-Id: ${Alibaba Cloud account ID}

Query parameters:

  • path (string, Optional): The directory path. Defaults to the current directory.

  • depth (integer, Optional): The traversal depth. The default value is 1. The minimum value is 1.

Response example:

{
  "path": "/home/user",
  "entries": [
    {
      "name": "example.txt",
      "type": "file",
      "path": "/tmp/code-interpreter-sandbox/home/user/example.txt",
      "size": 1024,
      "mode": 420,
      "permissions": "-rw-r--r--",
      "owner": "user",
      "group": "group",
      "modifiedTime": "2025-11-15T10:30:00Z"
    }
  ]
}

Retrieve file or directory information

Request syntax: GET ${BASEURL}/sandboxes/{sandboxId}/filesystem/stat

Request header: X-Acs-Parent-Id: ${Alibaba Cloud account ID}

Query parameters:

  • path (string, Required): The file or directory path.

Response example:

{
  "entry": {
    "name": "example.py",
    "type": "file",
    "path": "/workspace/example.py",
    "size": 1024,
    "mode": 420,
    "permissions": "-rw-r--r--",
    "owner": "user",
    "group": "group",
    "modifiedTime": "2025-11-15T10:30:00Z"
  }
}

Download a file

Request syntax: GET ${BASEURL}/sandboxes/{sandboxId}/filesystem/download

Request header: X-Acs-Parent-Id: ${Alibaba Cloud account ID}

Query parameters:

  • path (string, Required): The file path.

Response:

  • Content-Type: The Multipurpose Internet Mail Extensions (MIME) type of the file.

  • Content-Disposition: attachment; filename="example.txt"

  • Content-Length: The file size in bytes.

  • Response body: The binary stream of the file.

Note: Only file downloads are supported. Directory downloads are not supported.

Create a directory

Request syntax: POST ${BASEURL}/sandboxes/{sandboxId}/filesystem/mkdir

Request header: X-Acs-Parent-Id: ${Alibaba Cloud account ID}

  • Content-Type: application/json

Request body: application/json

{
  "path": "/tmp/home/user/testDir"  // Required. The directory path.
}

Notes:

  • This is an idempotent operation. If the directory already exists, a 200 status code is returned.

  • If parent directories do not exist, they are created automatically, similar to the `mkdir -p` command.

  • Recursive directory creation is supported.

Response example:

{
  "entry": {
    "name": "testDir",
    "type": "directory",
    "path": "/home/user/test_dir",
    "size": 0,
    "mode": 493,
    "permissions": "drwxr-xr-x",
    "owner": "user",
    "group": "group",
    "modifiedTime": "2025-11-15T10:30:00Z"
  }
}

Move or rename a file or directory

Request syntax: POST ${BASEURL}/sandboxes/{sandboxId}/filesystem/move

Request header: X-Acs-Parent-Id: ${Alibaba Cloud account ID}

  • Content-Type: application/json

Request body: application/json

{
  "source": "/workspace/old_name.txt",  // Required: Source file or directory path
  "destination": "/workspace/new_name.txt"  // Required: Destination file or directory path
}

Note:

  • Idempotency: If the source file does not exist and a file with the same name already exists at the destination, the operation returns 200.

  • This operation supports moving files across folders and renaming files within the same folder.

Response example:

{
  "entry": {
    "name": "new_name.txt",
    "type": "file",
    "path": "/workspace/new_name.txt",
    "size": 1024,
    "mode": 420,
    "permissions": "-rw-r--r--",
    "owner": "user",
    "group": "group",
    "modifiedTime": "2025-11-15T10:30:00Z"
  }
}

Delete a file or directory

Request syntax: POST ${BASEURL}/sandboxes/{sandboxId}/filesystem/remove

Request header: X-Acs-Parent-Id: ${Alibaba Cloud account ID}

  • Content-Type: application/json

Request body: application/json

{
  "path": "/home/user/test_dir"  // Required. The file or directory path.
}

Notes:

  • This is an idempotent operation. If the file or directory does not exist, a 200 status code is returned.

  • Recursive directory deletion is supported.

Response example:

{
  "entry": {
    "name": "testDir",
    "type": "directory",
    "path": "/home/user/test_dir",
    "size": 0,
    "mode": 493,
    "permissions": "drwxr-xr-x",
    "owner": "user",
    "group": "group",
    "modifiedTime": "2025-11-15T10:30:00Z"
  }
}

Upload a file

Request syntax: POST ${BASEURL}/sandboxes/{sandboxId}/filesystem/upload

Request header: X-Acs-Parent-Id: ${Alibaba Cloud account ID}

  • Content-Type: multipart/form-data

Request body: multipart/form-data

file: [binary]           // Required. The file content. Maximum 100 MB.
path: "uploads/example.txt"     // Optional. The destination file path. If not provided, the file name is used.
current_path: "."       // Optional. The current directory path. Used when `path` is not provided.

File limits:

  • Maximum file size: 100 MB

  • Only file uploads are supported. Directory creation is not supported.

  • Parent directories are created automatically if they do not exist.

Response example:

{
  "path": "uploads/example.txt",
  "size": 1024
}

Code execution

Execute code synchronously

Request syntax: POST ${BASEURL}/sandboxes/{sandboxId}/contexts/execute

Request header: X-Acs-Parent-Id: ${Alibaba Cloud account ID}

  • Content-Type: application/json

Request body: application/json

{
  "contextId": "kernel-12345-67890",  // Optional. The context ID. If provided, `language` is not required.
  "language": "python",  // Optional. The programming language type. Required only when `contextId` is not provided.
  "code": "print('hello')",  // Required. The code to execute.
  "timeout": 30  // Optional. The execution timeout in seconds. Default is 30. Maximum is 30.
}

Response example:

{
  "results": [
    {
      "type": "stdout",
      "text": "hello"
    },
    {
      "type": "result",
      "text": "None"
    },
    {
      "type": "endOfExecution",
      "status": "ok"
    }
  ],
  "contextId": "kernel-12345-67890"
}

Terminal execution

Execute commands synchronously

Execute commands synchronously

Request syntax: POST ${BASEURL}/sandboxes/{sandboxId}/processes/cmd

Request header: X-Acs-Parent-Id: ${Alibaba Cloud account ID}

  • Content-Type: application/json

Request body: application/json

{
  "command": "ls -la /home/user",  // Required. The command to execute.
  "cwd": "/tmp/code-interpreter-sandbox/home/user"  // Optional. The working directory.
}

Notes:

  • Hard timeout limit: The data plane gateway enforces a maximum execution time of 30 seconds.

  • Direct response: The complete command execution result is returned in the HTTP response.

  • No context required: Command execution does not require a context.

  • Scenarios: Suitable for simple commands, system checks, and file operations.

  • Interactive terminal: For an interactive terminal, use the /processes/tty WebSocket endpoint.

Response example:

{
  "executionId": "tty_exec_001",
  "status": "completed",
  "result": {
    "exitCode": 0,
    "stdout": "total 24\ndrwxr-xr-x 3 user user 4096 Jan 15 10:30 .",
    "stderr": "",
    "cwd": "/tmp/code-interpreter-sandbox/home/user",
    "executionTimeMs": 150
  },
  "executionTimeMs": 150
}

WebSocket interactive terminal endpoint

Request syntax: GET ${BASEURL}/sandboxes/{sandboxId}/processes/tty?protocol=json&tenantId={Alibaba Cloud account ID}

Request headers:

  • Connection: Upgrade (Required)

  • Upgrade: websocket (Required)

  • Sec-WebSocket-Key: {key} (Required)

  • Sec-WebSocket-Version: 13 (Required)

Query parameters:

  • protocol (string, Optional): The protocol mode for WebSocket communication.

    • json (Default): The JSON message format for structured messages.

    • text: The direct text stream format for xterm.js compatibility.

Response: 101 Switching Protocols

Notes:

  • Interactive terminal: Provides full bidirectional terminal communication.

  • Real-time I/O: Provides a real-time input/output stream with terminal control sequences.

  • Session persistence: Maintains the working directory, environment variables, and command history.

  • Terminal features: Supports color, cursor control, and terminal resizing.

  • No context required: TTY execution does not require a context.

  • Scenarios: Suitable for interactive shell sessions, system administration, and debugging.

Heartbeat keepalive mechanism:

  • Heartbeat interval: The client must send a ping message every 30 seconds.

  • Timeout detection: The server closes the connection if no heartbeat is received within 2 minutes.

  • Timeout warning: The server sends a warning message after 90 seconds of inactivity.

  • Session management: The TTY process is destroyed upon disconnection. A new session is created upon reconnection.

  • Automatic reconnection: The client is responsible for implementing automatic reconnection and session reconstruction.

Session behavior:

  • Connection loss: If the connection is lost, the TTY process terminates immediately and all running commands are stopped.

  • Reconnection: When the client reconnects, a new TTY session is created. The working directory and environment are reset.

  • State loss: Command history, running processes, and session state are lost upon disconnection.

  • Mitigation: To mitigate state loss, you can use tools such as screen or tmux to create persistent sessions that remain active after disconnection.

Message types (JSON mode):

  • input: Sends input to the terminal, such as keystrokes and commands.

  • output: Receives output from the terminal, such as stdout and stderr.

  • resize: Resizes the terminal.

  • status: Indicates a change in the terminal status.

  • ping/pong: Connection keepalive heartbeat.

  • connectionEstablished: Confirms the connection and includes session information.

  • timeoutWarning: Indicates that a connection timeout is about to occur.

  • connectionClosing: Notifies that the connection is closing.

JSON mode message examples:

Send input:

{
  "type": "input",
  "data": "ls -la\n"
}

Receive output:

{
  "type": "output",
  "data": "total 24\ndrwxr-xr-x 3 user user 4096 Jan 15 10:30 .\r\n",
  "stream": "stdout"
}

Resize:

{
  "type": "resize",
  "rows": 24,
  "cols": 80
}

Text mode (?protocol=text - for xterm.js):

  • Send: The client sends direct text data, such as keystrokes and commands.

  • Receive: The client receives direct terminal output, including ANSI escape codes.

  • Resize: A binary message of 8 bytes in big-endian format, consisting of 4 bytes for the number of rows and 4 bytes for the number of columns.

  • This mode does not use a JSON wrapper, which results in lower latency and better performance.

Process management

List all processes

Request syntax: GET ${BASEURL}/sandboxes/{sandboxId}/processes

Request header: X-Acs-Parent-Id: ${Alibaba Cloud account ID}

Query parameters: None

Response example:

{
  "items": [
    {
      "processId": 12345,
      "status": "running",
      "command": "python script.py",
      "tag": "my-process",
      "createdAt": "2025-11-15T10:30:00Z"
    }
  ],
  "total": 1
}

Retrieve process details by PID

Request syntax: GET ${BASEURL}/sandboxes/{sandboxId}/processes/{pid}

Path parameters:

  • pid (integer, Required): The process ID.

Request header: X-Acs-Parent-Id: ${Alibaba Cloud account ID}

Query parameters: None

Response example:

{
  "processId": 12345,
  "status": "running",
  "command": "python script.py",
  "tag": "my-process",
  "createdAt": "2025-11-15T10:30:00Z",
  "working_dir": "/tmp/sandbox/home/user",
  "environment": {
    "PATH": "/usr/bin:/bin",
    "HOME": "/tmp/sandbox/home/user"
  },
  "resourceUsage": {
    "cpuPercent": 10.5,
    "memoryMb": 128.0
  }
}

Force stop a process

Request syntax: DELETE ${BASEURL}/sandboxes/{sandboxId}/processes/{pid}

Path parameters:

  • pid (integer, Required): The ID of the process to stop.

Request header: X-Acs-Parent-Id: ${Alibaba Cloud account ID}

Query parameters: None

Notes:

  • This operation attempts to stop the process by sending a SIGTERM signal. If the process does not terminate, a SIGKILL signal is sent.

  • This is a destructive operation that terminates the process immediately.

Response example:

{
  "pid": 12345,
  "stopped": true,
  "stopped_at": "2025-11-15T10:35:00Z",
  "message": "Process stopped successfully"
}

Error responses

All error responses follow this format:

{
  "error": {
    "code": "ERROR_CODE",
    "message": "A human-readable error message.",
    "details": {
      // Additional error details (optional)
    }
  }
}

Common error codes

Status code

Error description

Recommended action

400

Invalid request parameters

Check the format and required fields of the request parameters.

401

Unauthorized access

Check the authentication information and permission settings.

404

Resource not found

Confirm that the resource ID and path are correct.

409

Resource conflict

The file already exists or there is a status conflict.

413

File too large

The file exceeds the 100 MB limit. Upload the file in parts or compress it.

500

Internal server error

Contact technical support.

507

Insufficient storage space

Clean up files and retry.

Error response format

{
  "code": "ERROR_CODE",
  "requestId": "abc123-def456-****",
  "message": "A detailed error message."
}

Retry policy

Implement a retry policy for the following errors:

  • 5xx Server Errors: Exponential Backoff Retries

  • 429 throttling errors: For 429 throttling errors, wait for a period of time before you retry.

  • 507 insufficient storage errors: For 507 insufficient storage errors, clean up files and then retry the operation.

More information

Resource management

  1. Clean up resources promptly:

    • Delete unnecessary files after tasks are complete.

    • Delete unused contexts and sessions promptly.

    • Monitor storage space usage.

  2. Set reasonable timeout periods:

    • Short-term tasks: For short-term tasks, use a shorter timeout period, such as 5 to 10 minutes.

    • Long-term tasks: For long-term tasks, use a longer timeout period, such as 30 minutes to 6 hours.

Code execution

  1. Error handling:

import traceback

try:
    # Your code
    result = some_function()
    print(f"Execution successful: {result}")
except Exception as e:
    print(f"Execution failed: {str(e)}")
    traceback.print_exc()
  1. Processing large data:

    • Use libraries such as pandas to read large files in chunks.

    • Release large objects from memory promptly.

    • Use generators to process large datasets.

  2. File operations:

import os
import pandas as pd

# Check if the file exists
if os.path.exists('/workspace/data.csv'):
    df = pd.read_csv('/workspace/data.csv')
    print(f"Read {len(df)} rows of data")

Security considerations

  1. Input validation:

    • Validate the type and size of uploaded files.

    • Check file paths to prevent directory traversal attacks.

  2. Access control:

    • Configure the `executionRoleArn` parameter based on the principle of least privilege.

    • Review and update credentials regularly.

  3. Data protection:

    • Delete sensitive data promptly after it is used.

    • Avoid hard coding sensitive information in your code.