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

Posted on

Question :

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

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


In the shell script I tried the following things but none of them work.

fooShell = python
#fooShell = $(python
#fooShell = echo "$(python"
Asked By: cppb


Answer #1:

You can print your value in Python, like this:

print fooPy()

and in your shell script:


Be sure not to leave spaces around the = in the shell script.

Answered By: Greg Hewgill

Answer #2:

In your Python code, you need to print the result.

import sys
def fooPy():
    return 10 # or whatever

if __name__ == '__main__':
    sys.stdout.write("%sn", fooPy())

Then in the shell, you can do:

fooShell=$(python # 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 🙂
Answered By: Alok Singhal

Answer #3:

If you want the value from the Python sys.exit statement, it will be in the shell special variable $?.

$ var=$(
$ returnval=$?
$ echo $var
Some string
$ echo returnval
Answered By: Dennis Williamson

Answer #4:

You should print the value returned by fooPy. The shell substitution reads from stdout. Replace the last line of your program with print fooPy() and then use the second shell pipeline you’ve mentioned. It should work.

Answered By: Noufal Ibrahim

Leave a Reply

Your email address will not be published. Required fields are marked *