Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a Python Data list to a bash array

Tags:

arrays

bash

list

I have a bash script that is calling a python script like so:

OUTPUT=$(python /path/path/script.py attr attr attr);

The python script will return a data list like so:

[item1, item2, item3]

How can I convert the $OUPUT variable which is a string of the return python data list into a bash array?

I'd like to read each item in bash if possible.

like image 917
altus Avatar asked Oct 02 '14 13:10

altus


2 Answers

Add () and | tr -d '[],':

OUTPUT=($(python /path/path/script.py attr attr attr | tr -d '[],'))

echo ${OUTPUT[0]}
echo ${OUTPUT[1]}
echo ${OUTPUT[2]}
echo ${OUTPUT[@]}

Output:

item1
item2
item3
item1 item2 item3
like image 61
Cyrus Avatar answered Nov 18 '22 09:11

Cyrus


You can make your script.py print a string that separates each item with spaces, which Bash will convert to an array, or you can use Bash to convert the return value of the python script into the format you want.

If you chose to print a string from your script.py you can use the following python code:

returnList = [1, 2, 3]
returnStr = ''
for item in returnList:
    returnStr += str(item)+' '
print(returnStr)

In this case, the output of the following bash script:

OUTPUT=$(python /path/to/script.py)
echo $OUTPUT
for i in $OUTPUT;
do
    echo $i
done

is:

1 2 3
1
2
3

Hope this helps you.

like image 8
alasimpara Avatar answered Nov 18 '22 08:11

alasimpara