close

How to pass a list as an environment variable?

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to pass a list as an environment variable in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

How to pass a list as an environment variable?

  1. How to pass a list as an environment variable?

    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"

  2. pass a list as an environment variable

    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"

Method 1

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)

Method 2

The environs PyPI package handles my use case well: 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
# required variables
gh_user = env("GITHUB_USER")  # => 'sloria'
secret = env("SECRET")  # => raises error if not set

# casting
max_connections = env.int("MAX_CONNECTIONS")  # => 100
ship_date = env.date("SHIP_DATE")  # => datetime.date(1984, 6, 25)
ttl = env.timedelta("TTL")  # => datetime.timedelta(0, 42)

# providing a default value
enable_login = env.bool("ENABLE_LOGIN", False)  # => True
enable_feature_x = env.bool("ENABLE_FEATURE_X", False)  # => False

# parsing lists
gh_repos = env.list("GITHUB_REPOS")  # => ['webargs', 'konch', 'ped']
coords = env.list("COORDINATES", subcast=float)  # => [23.3, 50.0]

Conclusion

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read