Python 如何将列表作为环境变量传递?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31352317/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to pass a list as an environment variable?
提问by CodingInCircles
I use a list as part of a Python program, and wanted to convert that to an environment variable.
我使用列表作为 Python 程序的一部分,并希望将其转换为环境变量。
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
我收到一个错误: 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?
如何修改我传递列表的方式,或获取它,以便在不使用 env 变量的情况下获得相同的输出?
采纳答案by Reut Sharabani
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:
在 Python 中:
list1 = [i.split(".") for i in os.environ.get("LIST_ITEMS").split(" ")]
for k, v in list1:
print(k, v)
回答by martineau
If you want to set the environment variable using that format, 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
回答by Martin Thoma
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.
如果您想在环境变量中构建数据,我建议使用 JSON。JSON 易于写入/读取,可以一行编写,解析器存在,开发人员都知道。
The solution
解决方案
To test, execute this in your shell:
要进行测试,请在您的 shell 中执行此操作:
$ export ENV_LIST_EXAMPLE='["Foo", "bar"]'
Python code to execute in the same shell:
要在同一个 shell 中执行的 Python 代码:
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
您感兴趣的可能性很高 cfg_load
回答by theY4Kman
The environsPyPI package handles my use case well: load a single setting from env var and coerce it to a list, int, etc:
在周围的PyPI包处理我的使用情况良好:从的环境变量加载一个单一的设置,并将其强制到一个列表,INT等:
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]