如何在Python中获取环境变量的值?
当前回答
您应该首先使用
import os
然后实际打印环境变量值
print(os.environ['yourvariable'])
当然,将变量替换为要访问的变量。
其他回答
您可以使用
import os
print os.environ
尝试查看PYTHONPATH或PYTHONHOME环境变量的内容。也许这会对你的第二个问题有所帮助。
如果您计划在生产web应用程序代码中使用该代码,使用Django和Flask等任何web框架,请使用envparse等项目。使用它,您可以将值读取为定义的类型。
from envparse import env
# will read WHITE_LIST=hello,world,hi to white_list = ["hello", "world", "hi"]
white_list = env.list("WHITE_LIST", default=[])
# Perfect for reading boolean
DEBUG = env.bool("DEBUG", default=False)
注意:kennetritz的autoenv是制作项目特定环境变量的推荐工具。对于使用autoenv的用户,请注意将.env文件保持为私有(公共无法访问)。
编辑日期: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。
您也可以尝试以下操作:
首先,安装python解耦
pip install python-decouple
将其导入到文件中
from decouple import config
然后获取环境变量
SECRET_KEY=config('SECRET_KEY')
在这里阅读有关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"))
推荐文章
- 把if-elif-else语句放在一行中?
- 我如何结合两个数据框架?
- 如何计数列表中唯一值的出现
- 为什么Pycharm的检查人员抱怨“d ={}”?
- 如何JSON序列化集?
- 在python中,年龄从出生日期开始
- 使用pip安装SciPy
- 在Python中,我应该如何测试变量是否为None, True或False
- 如何在Python中从毫秒创建datetime ?
- 如何解窝(爆炸)在一个熊猫数据帧列,成多行
- 如何使用pip安装opencv ?
- 在pip冻结命令的输出中“pkg-resources==0.0.0”是什么
- 从Docker容器获取环境变量
- 格式y轴为百分比
- 熊猫连接问题:列重叠但没有指定后缀