12

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)"
cppb
  • 2,319
  • 8
  • 32
  • 37

4 Answers4

34

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.

Greg Hewgill
  • 951,095
  • 183
  • 1,149
  • 1,285
  • 1
    thanks, that worked! I also made a mistake by putting spaces around =. So fixed that as well. – cppb Jan 22 '10 at 07:40
  • +1 for mentioning "Be sure not to leave spaces around the = in the shell script" It annoys the hell out of rookies like me. – Matt Bannert Aug 17 '10 at 13:23
11

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 :-)
Alok Singhal
  • 93,253
  • 21
  • 125
  • 158
5

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

$ var=$(foo.py)
$ returnval=$?
$ echo $var
Some string
$ echo returnval
10
fortran
  • 74,053
  • 25
  • 135
  • 175
Dennis Williamson
  • 346,391
  • 90
  • 374
  • 439
3

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.

Noufal Ibrahim
  • 71,383
  • 13
  • 135
  • 169