Skip to content

17.1 Skills 開發環境搭建

開發環境概述

開發 Skills 需要搭建合適的開發環境,包括必要的工具、依賴和配置。本節將詳細介紹如何搭建 Skills 開發環境。

环境要求

1. 系统要求

系统要求

操作系统

  • Linux(推薦 Ubuntu 20.04+)
  • macOS 10.15+
  • Windows 10+(需要 WSL2)

硬體要求

  • CPU: 4 核心及以上
  • 記憶體: 8GB 及以上(推薦 16GB)
  • 磁碟: 20GB 可用空間

軟體要求

  • Python 3.8+
  • Node.js 16+(可選,用於前端開發)
  • Git 2.20+
  • Docker 20+(可選,用於容器化)

2. 开发工具

推荐开发工具

代码编辑器

  • VS Code(推薦)
  • PyCharm
  • Sublime Text

版本控制

  • Git
  • GitHub Desktop(可選)

调试工具

  • Python Debugger (pdb)

  • VS Code Debugger

測試工具

  • pytest
  • unittest
  • coverage.py
yaml
## 环境安装

### 1\. Python 环境安装

#### 1.1 安装 Python

    bash


    # macOS
    brew install python@3.9

    # Ubuntu/Debian
    sudo apt update
    sudo apt install python3.9 python3.9-venv python3-pip

    # Windows
    # 从 https://www.python.org/downloads/ 下载安装程序

#### 1.2 创建虚拟环境

    bash


    # 创建虚拟环境
    python3 -m venv venv

    # 激活虚拟环境
    # macOS/Linux
    source venv/bin/activate

    # Windows
    venv\Scripts\activate

#### 1.3 安装依赖

    bash


    # 创建 requirements.txt
    cat > requirements.txt << EOF
    claude-code>=1.0.0
    pytest>=7.0.0
    pytest-cov>=4.0.0
    black>=23.0.0
    pylint>=2.17.0
    mypy>=1.0.0
    EOF

    # 安装依赖
    pip install -r requirements.txt

### 2\. Claude Code SDK 安装

#### 2.1 安装 SDK

    bash


    # 安装 Claude Code SDK
    pip install claude-code-sdk

    # 验证安装
    claude --version

#### 2.2 配置 SDK

    bash


    # 创建配置目录
    mkdir -p ~/.claude

    # 创建配置文件
    cat > ~/.claude/config.yaml << EOF
    version: "1.0"
    skills:
      development:
        enabled: true
        auto_reload: true
        log_level: DEBUG
    sdk:
      api_key: your_api_key_here
      endpoint: https://api.claudecode.com
    EOF

### 3\. 开发工具安装

#### 3.1 VS Code 扩展

## 推荐安装的 VS Code 扩展
  • Python
  • Pylance
  • Black Formatter
  • Pylint
  • pytest
  • GitLens
  • Docker
python
#### 3.2 配置 VS Code

    json


    {
        "python.defaultInterpreterPath": "${workspaceFolder}/venv/bin/python",
        "python.linting.enabled": true,
        "python.linting.pylintEnabled": true,
        "python.formatting.provider": "black",
        "python.testing.pytestEnabled": true,
        "python.testing.pytestArgs": [
            "tests"
        ],
        "editor.formatOnSave": true,
        "editor.codeActionsOnSave": {
            "source.organizeImports": true
        }
    }

## 项目初始化

### 1\. 创建项目结构

    bash


    # 创建项目目录
    mkdir my-skill
    cd my-skill

    # 创建项目结构
    mkdir -p src/skills
    mkdir -p tests
    mkdir -p docs
    mkdir -p examples
    mkdir -p scripts

### 2\. 初始化项目

#### 2.1 创建 setup.py

    python


    # setup.py
    from setuptools import setup, find_packages
    setup(
    name="my-skill",
    version="0.1.0",
    description="A custom Claude Code skill",
    author="Your Name",
    author_email="your.email@example.com",
    packages=find_packages(where="src"),
    package_dir={"": "src"},
    python_requires=">=3.8",
    install_requires=[
    "claude-code-sdk>=1.0.0",
    ],
    extras_require={
    "dev": [
    "pytest>=7.0.0",
    "pytest-cov>=4.0.0",
    "black>=23.0.0",
    "pylint>=2.17.0",
    "mypy>=1.0.0",
    ]
    },
    entry_points={
    "claude.skills": [
    "my_skill = skills.my_skill:MySkill",
    ]
    }
    )

    ~~~
    #### 2.2 创建 pyproject.toml

    ```toml

    # pyproject.toml

```json
    [build-system]
    requires = ["setuptools>=45", "wheel", "setuptools_scm>=6.2"]

    [project]
    name = "my-skill"
    version = "0.1.0"
    description = "A custom Claude Code skill"
    authors = [
        {name = "Your Name", email = "your.email@example.com"}
    ]
    requires-python = ">=3.8"
    dependencies = [
        "claude-code-sdk>=1.0.0",
    ]

    [project.optional-dependencies]
    dev = [
        "pytest>=7.0.0",
        "pytest-cov>=4.0.0",
        "black>=23.0.0",
        "pylint>=2.17.0",
        "mypy>=1.0.0",
    ]

    [project.entry-points."claude.skills"]
    my_skill = "skills.my_skill:MySkill"

    [tool.black]
    line-length = 88
    target-version = ['py38']

    [tool.pylint.messages_control]
    disable = [
        "C0111",  # missing-docstring
    ]

    [tool.pytest.ini_options]
    testpaths = ["tests"]
    python_files = ["test_*.py"]
    python_classes = ["Test*"]
    python_functions = ["test_*"]

#### 2.3 创建 README.md

    markdown
    # My Skill
    A custom Claude Code skill for demonstrating skill development.

    ## Installation

    ```bash

    pip install my-skill

## Usage

    bash
claude --skill my-skill --param value

Development

bash


# Install development dependencies
pip install -e ".[dev]"

# Run tests
pytest

# Run linting
pylint src/skills

# Format code
black src/skills

License


MIT

```python
    bash


    ~~~
    ### 3. 创建基础 Skill

    #### 3.1 创建 Skill 文件

    ```python

    # src/skills/my_skill.py

```python
    from typing import Dict, Any
    from claude_code_sdk import Skill, SkillContext, SkillResult

    class MySkill(Skill):
        def __init__(self):
            super().__init__(
                name="my-skill",
                version="0.1.0",
                description="A custom Claude Code skill"
            )

        def get_parameters_schema(self) -> Dict[str, Any]:
            return {
                "type": "object",
                "properties": {
                    "input": {
                        "type": "string",
                        "description": "Input text to process"
                    }
                },
                "required": ["input"]
            }

        def execute(self, parameters: Dict[str, Any], context: SkillContext) -> SkillResult:
            input_text = parameters["input"]
            # 处理输入
            output = self.process_input(input_text)
            return SkillResult(
                success=True,
                data={
                    "input": input_text,
                    "output": output
                }
            )

        def process_input(self, input_text: str) -> str:
            # 实现具体的处理逻辑
            return input_text.upper()

    bash
python
    #### 3.2 创建测试文件

    ```python

    # tests/test_my_skill.py

    import pytest
    from skills.my_skill import MySkill

    class TestMySkill:
        def setup_method(self):
            self.skill = MySkill()

        def test_skill_initialization(self):
            assert self.skill.name == "my-skill"
            assert self.skill.version == "0.1.0"

        def test_get_parameters_schema(self):
            schema = self.skill.get_parameters_schema()
            assert "properties" in schema
            assert "input" in schema["properties"]

        def test_execute(self):
            from claude_code_sdk import SkillContext

            parameters = {"input": "hello"}
            context = SkillContext()
            result = self.skill.execute(parameters, context)

            assert result.success
            assert result.data["output"] == "HELLO"

        def test_process_input(self):
            assert self.skill.process_input("hello") == "HELLO"
            assert self.skill.process_input("world") == "WORLD"

    ```

    ## 开发配置

    ### 1. 调试配置

    #### 1.1 VS Code 调试配置

    ```json

    // .vscode/launch.json
    {
    "version": "0.2.0",
    "configurations": [
    {
    "name": "Python: Current File",
    "type": "python",
    "request": "launch",
    "program": "${file}",
    "console": "integratedTerminal",
    "env": {
    "PYTHONPATH": "${workspaceFolder}/src"
    }
    },
    {
    "name": "Python: pytest",
    "type": "python",
    "request": "launch",
    "module": "pytest",
    "args": [
    "tests",
    "-v"
    ],
    "console": "integratedTerminal",
    "env": {
    "PYTHONPATH": "${workspaceFolder}/src"
    }
    }
    ]
    }


#### 1.2 日志配置

    python


```python
    # src/skills/logger.py
    import logging
    import sys

    def setup_logger(name: str, level: int = logging.DEBUG):
        logger = logging.getLogger(name)
        logger.setLevel(level)

        # 创建控制台处理器
        console_handler = logging.StreamHandler(sys.stdout)
        console_handler.setLevel(level)

        # 创建格式化器
        formatter = logging.Formatter(
            '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
        )
        console_handler.setFormatter(formatter)

        # 添加处理器
        logger.addHandler(console_handler)

        return logger

    # 使用示例
    logger = setup_logger(__name__)
    logger.debug("Debug message")
    logger.info("Info message")
    logger.warning("Warning message")
    logger.error("Error message")

### 2\. 测试配置

#### 2.1 pytest 配置

    python
python
    # tests/conftest.py
    import pytest
    from claude_code_sdk import SkillContext

    @pytest.fixture
    def skill_context():
        return SkillContext()

    @pytest.fixture
    def sample_parameters():
        return {
            "input": "test input"
        }

    bash
    #### 2.2 测试覆盖率配置

    ```bash

    # 執行測試並生成覆蓋率報告

    pytest --cov=src/skills --cov-report=html --cov-report=term

    # 生成覆蓋率報告

    pytest --cov=src/skills --cov-report=html
    open htmlcov/index.html

    ```

    ### 3. 代码质量配置

    #### 3.1 Black 配置

    ```ini

    # setup.cfg

    [tool:pytest]
    testpaths = tests

    [black]
    line-length = 88
    target-version = ['py38']
    include = '\.pyi?$'
    extend-exclude = '''
    /(

    # directories

    \.eggs
    | \.git
    | \.hg
    | \.mypy_cache
    | \.tox
    | \.venv
    | build
    | dist

    )/
    '''


#### 3.2 Pylint 配置

    ini


    # .pylintrc
    [MASTER]
    disable=C0111,C0103

    [FORMAT]
    max-line-length=88

    [DESIGN]
    max-args=7
    max-locals=15
    max-returns=6
    max-branches=12
    max-statements=50

#### 3.3 MyPy 配置

    ini


    # mypy.ini
    [mypy]
    python_version = 3.8
    warn_return_any = True
    warn_unused_configs = True
    disallow_untyped_defs = True

    [mypy-tests.*]
    disallow_untyped_defs = False

    bash
## 开发工作流
### 1. 开发流程

```markdown

## 開發流程

### 1. 功能開發

### 2. 程式碼審查

### 3. 釋出

```

### 2. Git 工作流

```bash

# 建立功能分支

git checkout -b feature/new-feature

# 提交程式碼

git add .
git commit -m "Add new feature"

# 推送到遠端

git push origin feature/new-feature

# 建立 Pull Request

# 在 GitHub 上建立 PR

# 合併後刪除分支

git checkout main
git pull origin main
git branch -d feature/new-feature
git push origin --delete feature/new-feature

3. 持续集成

3.1 GitHub Actions 配置

yaml
yaml
    # .github/workflows/ci.yml
    name: CI

    on:
      push:
        branches: [ main, develop ]
      pull_request:
        branches: [ main ]

    jobs:
      test:
        runs-on: ubuntu-latest

        steps:
        - uses: actions/checkout@v3

        - name: Set up Python
          uses: actions/setup-python@v4
          with:
            python-version: '3.9'

        - name: Install dependencies
          run: |
            python -m pip install --upgrade pip
            pip install -e ".[dev]"

    yaml
yaml
        - name: Lint with pylint
          run: |
            pylint src/skills

        - name: Format check with black
          run: |
            black --check src/skills

        - name: Type check with mypy
          run: |
            mypy src/skills

        - name: Test with pytest
          run: |
            pytest --cov=src/skills --cov-report=xml

        - name: Upload coverage to Codecov
          uses: codecov/codecov-action@v3
          with:
            file: ./coverage.xml

## 常见问题

### 1\. 安装问题

## 常见安装问题

### 问题:pip 安装失败
**解決方案** :

    bash


    # 升級 pip
    pip install --upgrade pip

    # 使用國內映象
    pip install -i https://pypi.tuna.tsinghua.edu.cn/simple my-skill

### 問題:依賴衝突

**解決方案** :

    bash


    # 使用虛擬環境
    python -m venv venv
    source venv/bin/activate

    # 使用 pip-tools
    pip install pip-tools
    pip-compile requirements.in
    pip-sync requirements.txt

### 2\. 執行問題

## 常見執行問題

### 問題:Skill 找不到

**解決方案** :

    bash


    # 確認 Skill 已註冊
    claude skill list

    # 重新安裝 Skill
    pip install -e .

    # 檢查 PYTHONPATH
    export PYTHONPATH="${PYTHONPATH}:$(pwd)/src"

### 問題:許可權錯誤

**解決方案** :

    bash


    # 檢查檔案許可權
    ls -la

    # 修改許可權
    chmod +x scripts/*.sh

    # 使用 sudo(不推薦)
    sudo pip install my-skill

### 3\. 除錯問題

## 常見除錯問題

### 問題:無法設定斷點

**解決方案** :

    python


    # 使用 pdb
    import pdb; pdb.set_trace()

    # 使用 ipdb
    import ipdb; ipdb.set_trace()

    # 使用 VS Code 偵錯程式
    # 在程式碼行號左側點選設定斷點

### 問題:日誌不輸出

**解決方案** :

    python


    # 確保日誌級別正確
    logger.setLevel(logging.DEBUG)

    # 新增處理器
    handler = logging.StreamHandler()
    logger.addHandler(handler)

    # 檢查日誌配置
    logging.basicConfig(level=logging.DEBUG)

基于 MIT 许可发布 | 永久导航