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:
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