Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

assigning value to shell variable using a function return value from Python

Tags:

python

shell

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)"
like image 830
cppb Avatar asked Jan 22 '10 07:01

cppb


People also ask

How does a shell function return a value?

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.

How do you return a value from another function in Python?

Simply call a function to pass the output into the second function as a parameter will use the return value in another function python.


2 Answers

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.

like image 192
Greg Hewgill Avatar answered Oct 15 '22 18:10

Greg Hewgill


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,
  • in "real programs", one should use sys.stdout.write() instead of print anyway :-)
like image 39
Alok Singhal Avatar answered Oct 15 '22 18:10

Alok Singhal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!