Mostly Linux & Python syntax notes and hyperlinks.

Friday, June 25, 2010

Linux/Python: setting shell variable to value returned from python function

From stackoverflow.com.  This works with python 2.4:
$ f=$(python foo.py)
$ echo $f
FOOO
Where foo.py is:
def foo():
  print "FOOO"

if __name__ == '__main__':
   foo()
There was a recommendation to use sys.stdout.write("%s\n", fooPy()) instead of print(), but I got an error about sys.stdout.write() expecting one not two input variables when I tried it. If I use sys.stdout.write("%s\n" % foo()) or print(foo()) in the main clause then the output is:
$ python foo.py
FOOO
None
$ w=$(python foo.py)
$ echo $w
FOOO None
With
import sys
def foo():
  sys.stdout.write("FOOO")
if __name__ == '__main__':
   foo()
I get
$ python foo.py
FOOO$
$ w=$(python foo.py)
$ echo $w
FOOO
$

No comments:

Post a Comment