DonnyFlaw
DonnyFlaw

Reputation: 690

How to convert Python list into Groovy list

I'm trying to handle Python script (that returns list of strings, e.g. ['1', '2', '3', 'latest']) output with Groovy (on Jenkins):

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']

Now I want to create HTML select node with all the elements from buildNumbers list as option nodes:

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

I expect to get

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

but instead it looks like

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

What should I change to make buildNumbers looks like a list, but not string?

Upvotes: 0

Views: 164

Answers (2)

Iterokun
Iterokun

Reputation: 2548

Your suggestion here with Eval.me() is really a hack. Think about it, you evaluate the output of the python script as a groovy script! Yes, accidentally python lists serialize into something that happens to be a valid groovy list, but what if it's a python dictionary or tuple? What if the strings have different escaping rules? It's just a bad idea.

Output json from your python script and parse json in your groovy script. It's a much happier place.

Upvotes: 1

Richard
Richard

Reputation: 177

The issue is that the output of your Python script is a string that looks like a list, not an actual list. When you call task.text, you're getting the entire output of the script as a single string.

To convert this string into a list of strings in Groovy, you can use the JsonSlurper class to parse JSON-formatted strings.

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

This script uses JsonSlurper().parseText() to parse the output of your Python script into a list of strings. The trim() function is just to remove any leading or trailing whitespace from the output.

Upvotes: 1

Related Questions