简体   繁体   English

无法使用 os.environ 访问 Python 脚本中的 Jenkins 环境变量

[英]Can't access Jenkins environment variables in Python script with os.environ

I am trying to run a python script in my Jenkins job that relies on Jenkins environment variables that have been set earlier.我正在尝试在我的 Jenkins 作业中运行 python 脚本,该作业依赖于之前设置的 Jenkins 环境变量。 The environment variables are set in my Jenkinsfile and when I echo them they are there.环境变量在我的 Jenkinsfile 中设置,当我回显它们时,它们就在那里。

But my python script fails when I try to access those variables with os.environ["VARIABLE"].但是当我尝试使用 os.environ["VARIABLE"] 访问这些变量时,我的 python 脚本失败。

This is how it is being set in my python script:这是在我的 python 脚本中设置的方式:
svn_branch = os.environ["SVN_BRANCH"]

And it fails with this error as though it can't find that variable:它失败并出现此错误,就好像它找不到该变量一样:

  File "c:\jenkins\workspace\test_jenkins_build.py", line 68, in <module>
    svn_branch = os.environ["SVN_BRANCH"]
  File "C:\Users\build\AppData\Local\Programs\Python\Python39\lib\os.py", line 679, in __getitem__
    raise KeyError(key) from None
KeyError: 'SVN_BRANCH'

Is there a way to have a python script access Jenkins environment variables?有没有办法让 python 脚本访问 Jenkins 环境变量? Thank you for any and all help!感谢您的任何帮助!

Please see below example: Jenkinsfile请看下面的例子:Jenkinsfile

stage('stage 1') {
              steps {
           script {
           dir ("C:\\python-workspace\\"){
               def result
               // Set your environment variable
               env.SVN_BRANCH= "app"
               result = bat label: 'Execute python script..', returnStatus: true, script: "hello.py "
              }
           }         
         }
   }

Python script: Python 脚本:

#!/usr/bin/python
import os
branch=os.environ['SVN_BRANCH']
print (branch)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM