How to pass variables from python script to bash script

I would print it to a file chosen on the command line then I'd get that value in bash with something like cat.

So you'd go:

python b.py tempfile.txt
var=`cat tempfile.txt`
rm tempfile.txt

[EDIT, another idea based on other answers]

Your other option is to format your output carefully so you can use bash functions like head/tail to pipe only the first/last lines into your next program.


I believe the answer is

.py

import sys 
a=['zero','one','two','three'] 
b = int(sys.argv[1]) 
###your python script can still print to stderr if it likes to 
print >> sys.stderr, "I am no converting" 
result = a[b] 
print result

.sh

#!/bin/sh 

num=2 
text=`python numtotext.py $num` 
echo "$num as text is $text" 

In your python script, redirect another messages to stderr, and print x to stdout:

import sys
...
print >>sys.stderr, "another message"
print x

in the bash script:

...
var=`python b.py 2>/dev/null`

Also, if x is an integer between 0,255, you can use exit code to pass it to the bash:

import sys
...
sys.exit(x)

in bash:

python b.py
var=$?

Please note that exit code is used to indicates errors, 0 means no error, and this breaks the convention.


I'm not sure about "better", but you could write the result to a file then read it back in in Bash and delete it afterwards.

This is definitely ugly, but it's something to keep in mind in case nothing else does the trick.


On bash backsticks works

I usualy do something like

PIP_PATH=`python -c "from distutils.sysconfig \
import get_python_lib; print(get_python_lib())"`


POWELINE_PATH=$PIP_PATH"/powerline"
echo $POWELINE_PATH