如何在Python中获取环境变量的值?


当前回答

以下是如何检查是否设置了$FOO:

try:  
   os.environ["FOO"]
except KeyError: 
   print "Please set the environment variable FOO"
   sys.exit(1)

其他回答

编辑日期: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。

您可以使用

import os
print os.environ

尝试查看PYTHONPATH或PYTHONHOME环境变量的内容。也许这会对你的第二个问题有所帮助。

在一行中使用嵌套for循环的棘手之处在于必须使用列表理解。因此,为了打印所有环境变量,而不必导入外部库,您可以使用:

python -c "import os;L=[f'{k}={v}' for k,v in os.environ.items()]; print('\n'.join(L))"

您也可以尝试以下操作:

首先,安装python解耦

pip install python-decouple

将其导入到文件中

from decouple import config

然后获取环境变量

SECRET_KEY=config('SECRET_KEY')

在这里阅读有关Python库的更多信息。

通过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))