Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 910
CodingInCircles Avatar asked Jul 11 '15 00:07

CodingInCircles


People also ask

Can an environment variable be an array?

short answer: yes, you can!

How do you pass an environment variable in Java?

How to access environment variables in Java. One of the most common ways is to use System. getenv(), which accepts an optional String argument. Based on whether a String argument is passed, a different value is returned from the method.


2 Answers

The rationale

I recommend using JSON if you want to have data structured in an environment variable. JSON is simple to write / read, can be written in a single line, parsers exist, developers know it.

The solution

To test, execute this in your shell:

$ export ENV_LIST_EXAMPLE='["Foo", "bar"]' 

Python code to execute in the same shell:

import os import json  env_list = json.loads(os.environ['ENV_LIST_EXAMPLE']) print(env_list) print(type(env_list)) 

gives

['Foo', 'bar'] <class 'list'> 

Package

Chances are high that you are interested in cfg_load

Debugging

If you see

JSONDecodeError: Expecting value: line 1 column 2 (char 1) 

You might have used single-quotes instead of double-quotes. While some JSON libraries accept that, the JSON standard clearly states that you need to use double-quotes:

Wrong: "['foo', 'bar']" Right: '["foo", "bar"]' 
like image 157
Martin Thoma Avatar answered Sep 18 '22 08:09

Martin Thoma


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) 
like image 23
Reut Sharabani Avatar answered Sep 20 '22 08:09

Reut Sharabani