How to create a common function to execute a python script in Jenkins

13,001

burnettk's answer is on the right track but incomplete. I am not aware of an official way to run python scripts directly so try the following workaround

Store your python script in a shared library specifically in the resources folder. (resources/yourscript.py)

Then import the file as a string and write it to a file. Eg:

script{
    def yourScriptAsaString = libraryResource '../resources/yourscript.py' 
    writeFile file: 'yourscript.py', text: yourScriptAsaString
    sh "python yourscript.py"
}
Share:
13,001
Nayana Adassuriya
Author by

Nayana Adassuriya

Updated on June 27, 2022

Comments

  • Nayana Adassuriya
    Nayana Adassuriya about 2 years

    I have a common python script which need to use in multiple pipeline jobs. What I did is create a qroovy file with common method as below.

    def create_slaves()
    {
        def cmd = 'python "-u my_script.py'
        def proc = cmd.execute()
        proc.waitfor()
    }
    return this
    

    execution threw this exception.

    Scripts not permitted to use staticMethod org.codehaus.groovy.runtime.DefaultGroovyMethods execute java.lang.String
    

    So I feel like this is not the correct approach. Someone has a clue about a suitable way for execute a common python script in pipeline?