如何将Python列表转换为Groovy列表

问题描述 投票:0回答:1

我正在尝试使用 Groovy(在 Jenkins 上)处理 Python 脚本(返回字符串列表,例如

['1', '2', '3', 'latest']
)输出:

def task = "python3 $JENKINS_HOME/scripts/my_script.py -p some_parameter".execute()
task.waitFor()
def buildNumbers = task.text  
// println buildNumbers returns the list as it is - ['1', '2', '3', 'latest']

现在我想创建 HTML

select
节点,其中
buildNumbers
列表中的所有元素作为
option
节点:

def htmlOptions = buildNumbers.collect { "<option value='${it}'>${it}</option>" }.join('\n') 
def htmlSelect = "<select name='SDK_version'>" + htmlOptions + "</select>" 
return htmlSelect

我期望得到

<select>
  <option>1</option>
  <option>2</option>
  <option>3</option>
  <option>latest</option>
</select>

但它看起来像

<select>
  <option>[</option>
  <option>'</option>
  <option>1</option>
  <option>'</option>
  ...
</select>

我应该更改什么才能使

buildNumbers
看起来像列表,而不是字符串?

groovy jenkins-groovy
1个回答
0
投票

问题在于 Python 脚本的输出是一个看起来像列表的字符串,而不是实际的列表。当您调用

task.text
时,您将获得脚本的整个输出作为单个字符串。

要将此字符串转换为 Groovy 中的字符串列表,可以使用 JsonSlurper 类来解析 JSON 格式的字符串。

import groovy.json.JsonSlurper

def task = "python3 $JENKINS_HOME/scripts/my_script.py -p some_parameter".execute()
task.waitFor()
def buildNumbers = new JsonSlurper().parseText(task.text.trim())

def htmlOptions = buildNumbers.collect { "<option value='${it}'>${it}</option>" }.join('\n') 
def htmlSelect = "<select name='SDK_version'>" + htmlOptions + "</select>" 
return htmlSelect

此脚本使用

JsonSlurper().parseText()
将 Python 脚本的输出解析为字符串列表。
trim()
函数只是从输出中删除任何前导或尾随空格。

© www.soinside.com 2019 - 2024. All rights reserved.