[Tutor] What is the python idiom to transfer Bash arrays to Python lists?
Alan Gauld
alan.gauld at yahoo.co.uk
Tue May 11 04:05:04 EDT 2021
On 11/05/2021 03:36, Jin Li wrote:
> Hi,
>
> I want to transfer Bash arrays into Python lists so that they can be
> used in the python script. For example,
>
> ```Bash
> arr1=(1 2 3)
> arr2=(a b c)
> # run main.py, and assign arr1 and arr2 to python list variables
> ```
>
> What is the python idiom to do this? Thank you.
There isn't really an idiom for doing this as its not a common
requirement. There are two possibilities that spring to mind:
1) assign the arrays to environment variables and
use os.getenv() from python
2) pass the arrays as command line arguments to
main.py and read them with sys.argv.
In both cases they will come to python as strings that
you will need to convert to lists using split() plus
whatever type conversions are necessary.
Here is an example:
############ testarr.sh ###
#! /bin/bash
a=(1,2,3)
echo "a is " $a
python testarr.py $a
echo "done"
########## testarr.py #####
import sys
L = [int(s) for s in sys.argv[-1].split(',')]
print('L=',L)
#############################
Which produces:
a is 1,2,3
L= [1, 2, 3]
done
HTH
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos
More information about the Tutor
mailing list