Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing python array to bash script (and passing bash variable to python function)

Tags:

python

bash

I have written a Python module which contains functions that return arrays. I want to be able to access the string arrays returned from the python module, and iterate over in a bash script, so I may iterate over the array elements.

For example:

Python module (mymod)

def foo():
    return ('String', 'Tuple', 'From', 'Python' )

def foo1(numargs):
    return [x for x in range(numargs)]

Bash script

foo_array  = .... # obtain array from mymod.foo()
for i in "${foo_array[@]}"
do
    echo $i
done


foo1_array = .... # obtain array from mymod.foo1(pass arg count from bash)
for j in "${foo1_array[@]}"
do
    echo $j
done

How can I implement this in bash?.

version Info:

Python 2.6.5 bash: 4.1.5

like image 560
Homunculus Reticulli Avatar asked Jul 09 '12 09:07

Homunculus Reticulli


2 Answers

Second try - this time shell takes the integration brunt.

Given foo.py containing this:

def foo():
        foo = ('String', 'Tuple', 'From', 'Python' )
        return foo

Then write your bash script as follows:

#!/bin/bash
FOO=`python -c 'from foo import *; print " ".join(foo())'`
for x in $FOO:
do
        echo "This is foo.sh: $x"
done

The remainder is first answer that drives integration from the Python end.

Python

import os
import subprocess

foo = ('String', 'Tuple', 'From', 'Python' )

os.putenv('FOO', ' '.join(foo))

subprocess.call('./foo.sh')

bash

#!/bin/bash
for x in $FOO
do
        echo "This is foo.sh: $x"
done
like image 50
Maria Zverina Avatar answered Nov 19 '22 11:11

Maria Zverina


In addition, you can tell python process to read STDIN with "-" as in

echo "print 'test'" | python -

Now you can define multiline snippets of python code and pass them into subshell

FOO=$( python - <<PYTHON

def foo():
    return ('String', 'Tuple', 'From', 'Python')

print ' '.join(foo())

PYTHON
)

for x in $FOO
do
    echo "$x"
done

You can also use env and set to list/pass environment and local variables from bash to python (into ".." strings).

like image 41
Yauhen Yakimovich Avatar answered Nov 19 '22 11:11

Yauhen Yakimovich