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

# Python Skill

> Execute Python code with configurable import and execution restrictions for data processing, automation, and custom logic.

<CardGroup cols={2}>
  <Card title="Type" icon="tag">
    `python`
  </Card>

  <Card title="Variants" icon="code-branch">
    Restricted Imports, Full Access
  </Card>
</CardGroup>

**Purpose:** The Python skill enables agents to execute Python code with fine-grained control over module imports, execution environment, and resource limits.

***

## Common Use Cases

<CardGroup cols={2}>
  <Card icon="chart-simple">
    **Data processing and analysis**

    Parse, transform, and analyze data with Python libraries
  </Card>

  <Card icon="file-code">
    **Running Python scripts**

    Execute automation scripts, data pipelines, and workflows
  </Card>

  <Card icon="plug">
    **API integrations**

    Call external APIs using requests, handle OAuth, process responses
  </Card>

  <Card icon="gear">
    **Custom business logic**

    Implement complex algorithms and domain-specific operations
  </Card>
</CardGroup>

***

## Variants Overview

| Variant                   | Security     | Key Permissions                   | Best For                        | Create Command                 |
| ------------------------- | ------------ | --------------------------------- | ------------------------------- | ------------------------------ |
| **Restricted Imports** 🟢 | Safe         | Standard library modules only     | Data processing, safe scripting | `--variant restricted_imports` |
| **Full Access** 🔴        | Unrestricted | All modules, third-party packages | Data science, ML workflows      | `--variant full_access`        |

<Tip>
  **Choosing a variant:** Start with Restricted Imports and only upgrade to Full Access when third-party packages are required. See [Variant Configuration](/core-concepts/skills/variant-configuration) for detailed differences.
</Tip>

***

## Configuration

**Example Configuration:**

```json theme={null}
{
  "allowed_imports": ["json", "csv", "datetime", "re", "math"],
  "timeout": 120,
  "max_memory": "512MB",
  "working_directory": "/workspace"
}
```

<AccordionGroup>
  <Accordion title="📋 Full Configuration Reference" icon="gear">
    | Parameter               | Type   | Default          | Description                         |
    | ----------------------- | ------ | ---------------- | ----------------------------------- |
    | `allowed_imports`       | array  | variant-specific | Whitelist of allowed Python modules |
    | `timeout`               | number | 120              | Execution timeout in seconds        |
    | `max_memory`            | string | "512MB"          | Memory limit for Python process     |
    | `max_output_size`       | string | "10MB"           | Maximum output capture size         |
    | `working_directory`     | string | "/"              | Execution directory                 |
    | `environment_variables` | object | {}               | Custom environment variables        |
  </Accordion>

  <Accordion title="⚙️ Variant-Specific Defaults" icon="code-branch">
    **Restricted Imports:**

    * `allowed_imports`: Standard library safe modules (json, csv, datetime, re, math, collections, itertools, etc.)
    * Network and shell access modules blocked

    **Full Access:**

    * `allowed_imports`: \["\*"] (all modules)
    * Third-party packages allowed
    * Higher default limits: `max_memory: "2GB"`, `timeout: 600`

    **See:** [Variant Configuration Guide](/core-concepts/skills/variant-configuration)
  </Accordion>
</AccordionGroup>

***

## Quick Start

```bash theme={null}
# Create skill with variant
kubiya skill create --name "Data Processor" --type python --variant restricted_imports --enabled

# Associate with agent
kubiya skill associate agent <agent-id> <skill-id>
```

<Card title="View Complete Examples" icon="lightbulb" href="/core-concepts/skills/examples#log-analyzer">
  See full data analysis patterns, API integration workflows, and ML pipeline configurations
</Card>

***

## Python Code Execution

### Inline Code Example

Agents can execute Python code directly:

```python theme={null}
import json
import datetime

data = {
    "timestamp": datetime.datetime.now().isoformat(),
    "status": "success",
    "results": [1, 2, 3, 4, 5]
}

print(json.dumps(data, indent=2))
```

### Script Execution

Agents can run Python scripts from the filesystem:

```python theme={null}
# /opt/scripts/process_logs.py
import sys
import json
from datetime import datetime

def analyze_logs(log_file):
    # Log processing logic
    results = {"processed": True, "count": 42}
    return results

if __name__ == "__main__":
    result = analyze_logs(sys.argv[1])
    print(json.dumps(result))
```

***

## Installing Additional Packages

For agents that need third-party packages, install them on the worker:

```bash theme={null}
# On the worker system
pip install requests pandas numpy

# Or use requirements.txt
pip install -r /opt/agent-requirements.txt
```

Then allow imports in the skill configuration:

```json theme={null}
{
  "allowed_imports": ["requests", "pandas", "numpy"]
}
```

<Info>
  **Package Management:** Packages must be installed on the worker system before agents can import them. Coordinate with your infrastructure team for package deployment.
</Info>

***

## Security Best Practices

<AccordionGroup>
  <Accordion title="Whitelist Required Imports Only" icon="list-check">
    Only allow the specific Python modules your agent needs.

    ```json theme={null}
    # Good: Specific imports
    allowed_imports: ["json", "csv", "datetime"]

    # Risky: Too permissive
    allowed_imports: ["*"]  # Allows everything
    ```
  </Accordion>

  <Accordion title="Set Memory Limits" icon="memory">
    Always configure `max_memory` to prevent resource exhaustion.

    ```json theme={null}
    max_memory: "512MB"  # Prevents memory exhaustion
    ```
  </Accordion>

  <Accordion title="Configure Timeouts" icon="clock">
    Set reasonable timeouts to prevent infinite loops.

    ```json theme={null}
    timeout: 120  # Scripts automatically terminate after 2 minutes
    ```
  </Accordion>
</AccordionGroup>

<Tip>
  **Performance Tip:** For data-heavy operations, consider increasing `max_memory` and `timeout` values appropriately.
</Tip>

***

## Troubleshooting & Related Skills

<AccordionGroup>
  <Accordion title="Import Error: Module Not Allowed" icon="ban">
    **Solutions:**

    * Add module to `allowed_imports` in configuration
    * Verify module name exactly matches Python import (e.g., `urllib.parse` not `urllib`)
    * Consider upgrading to Full Access variant if appropriate
  </Accordion>

  <Accordion title="Module Not Found" icon="triangle-exclamation">
    **Solutions:**

    * Verify package is installed on worker: `pip list | grep package-name`
    * Ensure `PYTHONPATH` includes package location
    * Install missing package: `pip install package-name`
  </Accordion>

  <Accordion title="Memory Limit Exceeded" icon="memory">
    **Solutions:**

    * Increase `max_memory` in configuration
    * Optimize script to use less memory (streaming, generators)
    * Process data in smaller batches
  </Accordion>
</AccordionGroup>

### Related Skills

<CardGroup cols={2}>
  <Card title="File System Skill" icon="folder-open" href="/core-concepts/skills/file-system">
    Read data files for Python processing
  </Card>

  <Card title="Shell Skill" icon="terminal" href="/core-concepts/skills/shell">
    Execute shell commands from Python
  </Card>

  <Card title="File Generation" icon="file-code" href="/core-concepts/skills/file-generation">
    Generate formatted output files
  </Card>

  <Card title="View All Skills" icon="layer-group" href="/core-concepts/skills/built-in-skills">
    Return to built-in skills overview
  </Card>
</CardGroup>
