I have a Python function, fooPy() that returns some value. ( int / double or string)
I want to use this value and assign it in a shell script. For example following is the python function:
def fooPy():
return "some string"
#return 10 .. alternatively, it can be an int
fooPy()
In the shell script I tried the following things but none of them work.
fooShell = python fooPy.py
#fooShell = $(python fooPy.py)
#fooShell = echo "$(python fooPy.py)"
return command is used to exit from a shell function. It takes a parameter [N], if N is mentioned then it returns [N] and if N is not mentioned then it returns the status of the last command executed within the function or script. N can only be a numeric value.
Simply call a function to pass the output into the second function as a parameter will use the return value in another function python.
You can print your value in Python, like this:
print fooPy()
and in your shell script:
fooShell=$(python fooPy.py)
Be sure not to leave spaces around the = in the shell script.
In your Python code, you need to print the result.
import sys
def fooPy():
return 10 # or whatever
if __name__ == '__main__':
sys.stdout.write("%s\n", fooPy())
Then in the shell, you can do:
fooShell=$(python fooPy.py) # note no space around the '='
Note that I added an if __name__ == '__main__' check in the Python code, to make sure that the printing is done only when your program is run from the command line, not when you import it from the Python interpreter.
I also used sys.stdout.write() instead of print, because
print has different behavior in Python 2 and Python 3,sys.stdout.write() instead of print anyway :-)If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With