如何在Python中获取环境变量的值?
当前回答
您可以使用python dotenv模块访问环境变量
使用以下方法安装模块:
pip install python-dotenv
然后将模块导入Python文件
import os
from dotenv import load_dotenv
# Load the environment variables
load_dotenv()
# Access the environment variable
print(os.getenv("BASE_URL"))
其他回答
您应该首先使用
import os
然后实际打印环境变量值
print(os.environ['yourvariable'])
当然,将变量替换为要访问的变量。
编辑日期:2021 10月
以下是@Peter的评论,您可以如何测试它:
主.py
#!/usr/bin/env python
from os import environ
# Initialize variables
num_of_vars = 50
for i in range(1, num_of_vars):
environ[f"_BENCHMARK_{i}"] = f"BENCHMARK VALUE {i}"
def stopwatch(repeat=1, autorun=True):
"""
Source: https://stackoverflow.com/a/68660080/5285732
stopwatch decorator to calculate the total time of a function
"""
import timeit
import functools
def outer_func(func):
@functools.wraps(func)
def time_func(*args, **kwargs):
t1 = timeit.default_timer()
for _ in range(repeat):
r = func(*args, **kwargs)
t2 = timeit.default_timer()
print(f"Function={func.__name__}, Time={t2 - t1}")
return r
if autorun:
try:
time_func()
except TypeError:
raise Exception(f"{time_func.__name__}: autorun only works with no parameters, you may want to use @stopwatch(autorun=False)") from None
return time_func
if callable(repeat):
func = repeat
repeat = 1
return outer_func(func)
return outer_func
@stopwatch(repeat=10000)
def using_environ():
for item in environ:
pass
@stopwatch
def using_dict(repeat=10000):
env_vars_dict = dict(environ)
for item in env_vars_dict:
pass
python "main.py"
# Output
Function=using_environ, Time=0.216224731
Function=using_dict, Time=0.00014206099999999888
如果这是真的。。。使用dict()比直接访问environ快1500倍。
性能驱动的方法-调用environ是昂贵的,因此最好调用一次并将其保存到字典中。完整示例:
from os import environ
# Slower
print(environ["USER"], environ["NAME"])
# Faster
env_dict = dict(environ)
print(env_dict["USER"], env_dict["NAME"])
P.S-如果您担心暴露私有环境变量,那么在赋值后清理env_dict。
通过os.environ访问环境变量:
import os
print(os.environ['HOME'])
要查看所有环境变量的列表,请执行以下操作:
print(os.environ)
如果密钥不存在,尝试访问它将引发KeyError。要避免这种情况:
# Returns `None` if the key doesn't exist
print(os.environ.get('KEY_THAT_MIGHT_EXIST'))
# Returns `default_value` if the key doesn't exist
print(os.environ.get('KEY_THAT_MIGHT_EXIST', default_value))
# Returns `default_value` if the key doesn't exist
print(os.getenv('KEY_THAT_MIGHT_EXIST', default_value))
在一行中使用嵌套for循环的棘手之处在于必须使用列表理解。因此,为了打印所有环境变量,而不必导入外部库,您可以使用:
python -c "import os;L=[f'{k}={v}' for k,v in os.environ.items()]; print('\n'.join(L))"
至于环境变量:
import os
print os.environ["HOME"]
推荐文章
- 如何排序mongodb与pymongo
- 不可变与可变类型
- 列表是线程安全的吗?
- 操作系统。makdirs在我的路径上不理解“~”
- 如何在Django模板中获得我的网站的域名?
- 在django Forms中定义css类
- 如何在Python中scp ?
- Numpy Max vs amax vs maximum
- 我应该在.gitignore文件中添加Django迁移文件吗?
- 每n行有熊猫
- 实例属性attribute_name定义在__init__之外
- 如何获取在Python中捕获的异常的名称?
- 第一次出现的值大于现有值的Numpy
- 如何在POM.xml中引用环境变量?
- 如何从Python函数中返回两个值?