Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return multiple variables from python to bash

I have a bash script that calls a python script. At first I was just returning one variable and that is fine, but now I was told to return two variables and I was wondering if there is a clean and simple way to return more than one variable.

archiveID=$(python glacier_upload.py $archive_file_name $CURRENTVAULT)

Is the call I make from bash

print archive_id['ArchiveId']
archive_id['ArchiveId']

This returns the archive id to the bash script

Normally I know you can use a return statement in python to return multiple variables, but with it just being a script that is the way I found to return a variable. I could make it a function that gets called but even then, how would I receive the multiple variables that I would be passing back?

like image 448
Tall Paul Avatar asked Jun 21 '13 15:06

Tall Paul


People also ask

How do you return multiple variables in Python?

In Python, you can return multiple values by simply return them separated by commas. In Python, comma-separated values are considered tuples without parentheses, except where required by syntax.

Can bash function return multiple values?

Yes, bash 's return can only return numbers, and only integers between 0 and 255.

Can you return multiple variables?

Python functions can return multiple variables. These variables can be stored in variables directly. A function is not required to return a variable, it can return zero, one, two or more variables.

Can we return multiple values from a function in Python?

Python functions can return multiple values. These values can be stored in variables directly. A function is not restricted to return a variable, it can return zero, one, two or more values.


1 Answers

From your python script, output one variable per line. Then from you bash script, read one variable per line:

Python

print "foo bar"
print 5

Bash

#! /bin/bash

python main.py | while read line ; do
    echo $line
done

Final Solution:

Thanks Guillaume! You gave me a great starting point out the soultion. I am just going to post my solution here for others.

#! /bin/bash

array=()
while read line ; do
  array+=($line)
done < <(python main.py)
echo ${array[@]}

I found the rest of the solution that I needed here

like image 122
Guillaume Avatar answered Oct 15 '22 09:10

Guillaume