You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Bash生成Python版本对应JSON映射适配GitHub Actions

GitHub Actions中Bash实现Python主次版本到完整版本的JSON映射

核心实现思路

  • 预先定义主次版本与完整版本的映射关系(手动维护更稳定,也可动态获取)
  • 解析输入的逗号分隔主次版本列表,筛选出有效条目
  • 生成符合JSON规范的键值对映射,输出为GitHub Actions变量供后续Job调用

具体实现步骤

1. 生成版本映射JSON的Job

jobs:
  generate-python-version-map:
    runs-on: ubuntu-latest
    outputs:
      version-map: ${{ steps.build-map.outputs.version-map }}
    steps:
      - name: Build Python version mapping
        id: build-map
        run: |
          # 手动维护主次版本到完整版本的映射(按需更新)
          declare -A version_map=(
            ["3.8"]="3.8.18"
            ["3.9"]="3.9.17"
            ["3.10"]="3.10.12"
            ["3.11"]="3.11.4"
            ["3.12"]="3.12.0"
          )

          # 接收输入的逗号分隔版本列表(示例从workflow输入获取)
          input_versions="${{ inputs.target-python-versions }}"

          # 构建JSON字符串
          json_result="{"
          first_item=true
          for ver in $(echo "$input_versions" | tr ',' ' '); do
            if [[ -n "${version_map[$ver]}" ]]; then
              if [ "$first_item" = true ]; then
                first_item=false
              else
                json_result="$json_result,"
              fi
              json_result="$json_result\"$ver\":\"${version_map[$ver]}\""
            fi
          done
          json_result="$json_result}"

          # 将结果输出到GitHub Actions变量
          echo "version-map=$json_result" >> "$GITHUB_OUTPUT"

2. 后续Job中调用映射作为matrix参数

run-python-tests:
    needs: generate-python-version-map
    runs-on: ubuntu-latest
    strategy:
      matrix:
        # 解析JSON映射,matrix会自动遍历所有键值对
        python-version: ${{ fromJson(needs.generate-python-version-map.outputs.version-map) }}
    steps:
      - name: Set up Python ${{ matrix.python-version }}
        uses: actions/setup-python@v5
        with:
          python-version: ${{ matrix.python-version }}
      # 这里添加测试、构建等后续步骤

可选:动态获取最新Patch版本

如果不想手动维护版本,可通过python-build工具查询指定主次版本的最新完整版本:

# 安装依赖
sudo apt-get update && sudo apt-get install -y python-build

# 定义函数获取最新Patch版本
get_latest_patch() {
  local major_minor=$1
  python-build --list | grep "^$major_minor\." | sort -V | tail -n1
}

# 替换手动映射的赋值逻辑
version_map["3.8"]=$(get_latest_patch "3.8")
version_map["3.9"]=$(get_latest_patch "3.9")

注意事项

  • 输入的主次版本若不在映射中会被自动忽略,避免无效版本触发错误
  • 动态获取版本依赖网络和python-build的版本列表,稳定性略低于手动维护
  • 构建JSON时需严格控制引号和逗号,确保符合fromJson函数的解析要求

内容的提问来源于stack exchange,提问作者pkaramol

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 15:35:25