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


当前回答

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

其他回答

检查密钥是否存在(返回True或False)

'HOME' in os.environ

您也可以在打印密钥时使用get();如果要使用默认值,则非常有用。

print(os.environ.get('HOME', '/home/username/'))

其中/home/username/是默认值

import os
for a in os.environ:
    print('Var: ', a, 'Value: ', os.getenv(a))
print("all done")

这将打印所有环境变量及其值。

您也可以尝试以下操作:

首先,安装python解耦

pip install python-decouple

将其导入到文件中

from decouple import config

然后获取环境变量

SECRET_KEY=config('SECRET_KEY')

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

还有许多很棒的图书馆。例如,环境将允许您解析环境变量中的对象,即rad。例如:

from envs import env
env('SECRET_KEY') # 'your_secret_key_here'
env('SERVER_NAMES',var_type='list') #['your', 'list', 'here']

实际上可以这样做:

import os

for item, value in os.environ.items():
    print('{}: {}'.format(item, value))

或者简单地:

for i, j in os.environ.items():
    print(i, j)

要查看参数中的值:

print(os.environ['HOME'])

Or:

print(os.environ.get('HOME'))

要设置值,请执行以下操作:

os.environ['HOME'] = '/new/value'