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

如何从Azure Pipeline传递参数至Python脚本?问题排查与修正

问题:Azure DevOps Pipeline参数无法传递给Python脚本

用户在Azure DevOps Pipeline中定义了用户输入参数,尝试传递给Python脚本,但Python中获取的参数为空,尽管打印os.environ能看到该变量存在。

原始YAML配置

parameters:
- name: Action123
  displayName: 'Select Action'
  type: string
  default: 'enable'
  values:
  - 'enable'
  - 'disable'

trigger: none
stages:
- stage: Create
  pool: 
   name: sdasdasd
   demands:
    - agent.name -equals sdasdasd
  jobs:
  - job: BuildJob
    steps:
    - script: echo Building!
    - task: Bash@3
      inputs:
        targetType: 'inline'
        script: |
          export Action123=$(Action123)
          python job/job-action.py

    - task: Bash@3
      inputs:
        targetType: 'inline'
        script: |
          echo 'Action123 Taken =========>>>' + $(Action123)
      displayName: Summary for Dev Action Utility

原始Python脚本

import requests
import json
import os


Action123 = os.getenv('Action123')

print("Action123 ===========>>> " + Action123) #This is not getting printed

问题原因

  1. Pipeline参数引用语法错误:在Bash任务中,引用Pipeline的parameters需要使用${{ parameters.参数名 }}语法,而你用的$(Action123)是引用Pipeline变量(variables)的语法,无法正确解析参数值,导致export的变量实际为空。
  2. Bash字符串拼接错误:第二个Bash任务中echo 'xxx' + $(Action123)的写法不符合Bash语法,应该用空格连接字符串,但这不是Python脚本获取不到值的直接原因。

修正方案

1. 修改YAML配置

将Bash任务中引用参数的语法修正为${{ parameters.Action123 }},同时修复echo的拼接方式:

parameters:
- name: Action123
  displayName: 'Select Action'
  type: string
  default: 'enable'
  values:
  - 'enable'
  - 'disable'

trigger: none
stages:
- stage: Create
  pool: 
   name: sdasdasd
   demands:
    - agent.name -equals sdasdasd
  jobs:
  - job: BuildJob
    steps:
    - script: echo Building!
    - task: Bash@3
      inputs:
        targetType: 'inline'
        script: |
          # 正确引用Pipeline参数
          export Action123=${{ parameters.Action123 }}
          python job/job-action.py

    - task: Bash@3
      inputs:
        targetType: 'inline'
        script: |
          # Bash中字符串拼接用空格,不需要+
          echo 'Action123 Taken =========>>>' ${{ parameters.Action123 }}
      displayName: Summary for Dev Action Utility

2. (可选)优化Python脚本

为避免变量为空时出现拼接错误,可以添加空值判断:

import requests
import json
import os

# 设置默认值避免空值导致报错
Action123 = os.getenv('Action123', '未获取到值')  

# 使用f-string让输出更简洁
print(f"Action123 ===========>> {Action123}")  

验证逻辑

修正后,Bash任务会正确将Pipeline参数值导出为环境变量,Python脚本通过os.getenv就能获取到正确的参数值,print语句也能正常输出。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 13:45:17