77

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?

9 Answers 9

149

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"]'
8
  • 5
    This should be the accepted answer to me.
    – Nam G VU
    Jan 4, 2021 at 23:35
  • JSONDecodeError: Expecting value: line 1 column 2 (char 1) Oct 1, 2021 at 21:30
  • @GonzaloGarcia I have no clue what you want to tell me. You might be interested in How do I ask a good question Oct 2, 2021 at 6:14
  • 2
    @daniel451 Double quotes are correct JSON, single quotes are not. Depending on the JSON libary it might still work, but that's a decision to ignore this part of the standard: json.org/json-en.html Jan 26, 2022 at 13:13
  • 2
    @GonzaloGarcia I got the same error when I used double quotes on the outside and single inside. It appears to only work with '["foo", "bar"]' Mar 3, 2022 at 0:58
35

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)
4
  • 2
    The reason why I'd like to use env variables is because I can make a config file with stuff I'd use in the code, source it and if I need to make changes, just change the config file, rather than touch the code. I'll try yours and @martineau's answers and mark one of them as the answer. Thanks! :) Jul 11, 2015 at 21:56
  • 1
    Why not put it in some storage (like a file) and refer to that storage? Feb 25, 2019 at 9:24
  • I am getting this error when I export LIST_ITEMS: export: `=a.1 b.2 c.3': not a valid identifier
    – AnujaP
    Jul 30, 2020 at 18:43
  • This is actually helpful in my case as I am storing my Env Vars in a JSON to pass them to SAM local invoke command. Jan 17 at 1:35
31

The environs PyPI package handles this use case well.

Make sure your env var is in csv format:

export GITHUB_REPO_PRIORITY="webargs,konch,ped"

Load a single setting from env var and coerce it to a list, int, etc:

from environs import Env

env = Env()
env.read_env()  # read .env file, if it exists

# parsing lists
#  env: GITHUB_REPOS=webargs,konch,ped
gh_repos = env.list("GITHUB_REPOS")  # => ['webargs', 'konch', 'ped']
#  env: COORDINATES=23.3,50.0
coords = env.list("COORDINATES", subcast=float)  # => [23.3, 50.0]
# provide default value if env not set
gh_repos = env.list("GITHUB_REPOS", []) # => []
2
  • 1
    Good answer but a bit frustrating because there is not example of how I should set it in the actual env. Solution is to set the env in csv format: eg. GITHUB_REPOS="webargs,konch,ped" May 4, 2022 at 10:53
  • Mmm, that's a very good point. I've edited the answer to include the env var values for each example
    – theY4Kman
    May 4, 2022 at 17:33
6

If you want to set the environment variable using that format — ['a.1','b.2','c.3'] — this would work:

from ast import literal_eval

list1 = [literal_eval(e.strip()) for e in os.environ["LIST_ITEMS"].split(',')]
for item in list1:
    alpha,number = item.split('.')
    print alpha, number

Output:

a 1
b 2
c 3
2
YOUR_VARIABLE="val1, val2"

In your Python code, Just split them as a list

import os
os.environ.get('YOUR_VARIABLE').split(', ')
1
export FILES="test1.txt,test2.txt"

In python script

import os
FILES = os.getenv("FILES").split(",")

print(FILES)
print(type(FILES))

Output:

['test1.txt', 'test2.txt']
<class 'list'>
1

We can also use eval function to transform a string to a list

Setup env vars:

export ENV_LIST_1='["Foo", "bar"]'
export ENV_LIST_2="['Foo', 'bar']"

Python code to execute in the same shell:

import os

env_list1 = eval(os.environ['ENV_LIST_1'])
env_list2 = eval(os.environ['ENV_LIST_2'])

print(env_list1, type(env_list1))
print(env_list2, type(env_list2))

Result:

['Foo', 'bar'], list
['Foo', 'bar'], list
0

In .env:

    VAR="val1,val2..."

In python code:

    from dotenv import load_dotenv
    load_dotenv('/path/to/your/file.env')
    value = os.getenv('VAR').split(',')

It's work for send for email's list

-2

So no matter what I tried, i could not send emails to multiple recipients with smtplib. The only solution that worked out for me is to for loop the recipients

import smtplib
from email.mime.text import MIMEText

s = smtplib.SMTP('smtp.freesmtpservers.com')
# s.set_debuglevel(1)
recipients = ['[email protected]','[email protected]','[email protected]','[email protected]']

for x in recipients:
    msg = MIMEText("""body""")
    sender = '[email protected]'
    msg['Subject'] = "subject line"
    msg['From'] = sender
    msg['To'] = str(x)
    s.sendmail(sender, str(x), msg.as_string())
1
  • irrelevant to this question
    – Natacha
    Jan 14 at 17:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.