简体   繁体   中英

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. The environment variables are set in my Jenkinsfile and when I echo them they are there.

But my python script fails when I try to access those variables with os.environ["VARIABLE"].

This is how it is being set in my python script:
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? Thank you for any and all help!

Please see below example: 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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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