首页 > 解决方案 > 更新文件中的值并忽略python中的变量是否没有输入

问题描述

我从詹金斯到 python 的变量很少。此 python 获取文件作为输入并检查特定内容并将值替换为通过 jenkins 提供的用户输入。

我的要求是,当没有通过 jenkins 提供输入时,文件中的值应该与以前相同。目前对我来说,它被替换为None. 请就此提出建议。

提前致谢!

我的 Python 代码如下:

import fileinput
import os

username = os.getenv("username")
Password = os.getenv("Password")
hostname = os.getenv("hostname")

for line in fileinput.input('C:\\Jenkinsfile_test', inplace=True):
    if line.startswith('def username'):
        print "def username=",username
    elif line.startswith('def Password'):
        print "def Password=",Password
    elif line.startswith('def hostname'):
        print "def hostname=",hostname
    else:
        print line.strip()

我的 Jenkinsfile_test 如下,

def skipRemainingStages = false

def username=un
def Password=pwd
def hostname=host

pipeline {
    agent any
    stages {
        stage('test') {
            steps {
                .......
            }
        }
    }
}

标签: pythonjenkins

解决方案


我刚刚添加了一个检查,确认环境已为每个条件提供了一个值。

for line in fileinput.input('C:\\Jenkinsfile_test', inplace=True):
    if line.startswith('def username') and username is not None:
        print "def username=",username
    elif line.startswith('def Password') and Password is not None:
        print "def Password=",Password
    elif line.startswith('def hostname') and hostname is not None:
        print "def hostname=",hostname
    else:
        print line.strip()

推荐阅读