CodingInCircles CodingInCircles - 3 months ago 18
Python Question

How to pass a list as an environment variable?

I use a list as part of a Python program, and wanted to convert that to an environment variable.

So, it's like this:

list1 = ['a.1','b.2','c.3']
for items in list1:
alpha,number = items.split('.')
print(alpha,number)


which gives me, as expected:

a 1
b 2
c 3


But when I try to set it as an environment variable, as:

export LIST_ITEMS = 'a.1', 'b.2', 'c.3'


and do:

list1 = [os.environ.get("LIST_ITEMS")]
for items in list1:
alpha,number = items.split('.')
print(alpha,number)


I get an error:
ValueError: too many values to unpack


How do I modify the way I pass the list, or get it so that I have the same output as without using env variables?

Answer Source

I'm not sure why you'd do it through the environment variables, but you can do this:

export LIST_ITEMS ="a.1 b.2 c.3"

And in Python:

list1 = [i.split(".") for i in os.environ.get("LIST_ITEMS").split(" ")] 

for k, v in list1:
    print(k, v)