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

I wrote a Python module that contains functions that return arrays. I want to have access to the string arrays returned from the python module and iterate over them in a bash script, so I can iterate over the elements of the array.

For instance:

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 to implement this in bash ?.

Version Information:

Python 2.6.5 bash: 4.1.5

+5
source share
5 answers

The second attempt - this time shell accepts the main integration challenge.

This foo.py contains the following:

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

Then write a 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 rest is the first answer that drives integration from the end of Python.

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
+13
source

, , python STDIN "-",

echo "print 'test'" | python -

python

FOO=$( python - <<PYTHON

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

print ' '.join(foo())

PYTHON
)

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

env / bash python ( ".." ).

+1

, - , , , , .

- :

> python script.py | sh shellscript.sh
0

. script.py:

 a = ['String','Tuple','From','Python']

    for i in range(len(a)):

            print(a[i])

bash pyth.sh

#!/bin/bash

python script.py > tempfile.txt
readarray a < tempfile.txt
rm tempfile.txt

for j in "${a[@]}"
do 
      echo $j
done

sh pyth.sh

0

Like the Maria method for getting output from python, you can use the library argparseto enter variables into python scripts from bash; There are tutorials and additional documents here for Python 3 and here for python 2.

Python script example command_line.py:

import argparse
import numpy as np

if __name__ == "__main__":

    parser = argparse.ArgumentParser()

    parser.add_argument('x', type=int)

    parser.add_argument('array')

    args = parser.parse_args()

    print(type(args.x))
    print(type(args.array))
    print(2 * args.x)

    str_array = args.array.split(',')
    print(args.x * np.array(str_array, dtype=int))

Then from the terminal:

$ python3 command_line.py 2 0,1,2,3,4
# Output
<class 'int'>
<class 'str'>
4
[0 2 4 6 8]
0
source

All Articles