Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Capture the return value from python script ran in Jenkins sh

I have the following python script myscript.py:

#!/usr/bin/python
def main():
    return "hello"

if __name__ == '__main__':
    main()

And I run that script from the Jenkins groovy:

returnValue = sh(returnStdout: true, script: "python3.9 -u scripts/myscript.py")
log.info("returnValue: ${returnValue}")

I expect to see returnValue: hello in the logs but I see returnValue:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I understand that returnStdout: true returns standard output from the python script, and since there is no standard output the returnValue is null resulting in returnValue:

To prove my point, I modify my python script to print "hello" instead of returning it as following:

#!/usr/bin/python
def main():
    print("hello")

if __name__ == '__main__':
    main()

And now I get returnValue: hello from Jenkins log.

Even though the implementation with the print instead of return works it just doesn’t feel right and very confusing.
Is this behavior correct?
Or is there a way to actually use return keyword in the python script and store the returned value in the variable inside the Jenkins groovy file?

>Solution :

This behavior is correct. When you use return in the function it means that specific function is returning the string, but it has nothing to do with StdOut. Using print or any other function that echos to stdout (e.g. logging) makes sure the output is captured by Jenkins and available as returnValue

As an additional example, if your script looked like the following:

if __name__=='__main__':
    s = main()

In your first example the string "hello" would be assigned to s, in your second example, however, s would be None because the string is logged to stdout

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading