简体   繁体   English

如何在 Python 中访问环境变量?

[英]How do I access environment variables in Python?

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

Environment variables are accessed through os.environ :环境变量通过os.environ访问:

import os
print(os.environ['HOME'])

To see a list of all environment variables:要查看所有环境变量的列表:

print(os.environ)

If a key is not present, attempting to access it will raise a KeyError .如果键不存在,尝试访问它会引发KeyError To avoid this:为了避免这种情况:

# Returns `None` if key doesn't exist
print(os.environ.get('KEY_THAT_MIGHT_EXIST'))

# Returns `default_value` if key doesn't exist
print(os.environ.get('KEY_THAT_MIGHT_EXIST', default_value))

# Returns `default_value` if key doesn't exist
print(os.getenv('KEY_THAT_MIGHT_EXIST', default_value))

To check if the key exists (returns True or False )检查密钥是否存在(返回TrueFalse

'HOME' in os.environ

You can also use get() when printing the key;打印密钥时也可以使用get() useful if you want to use a default.如果您想使用默认值,这很有用。

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

where /home/username/ is the default其中/home/username/是默认值

Here's how to check if $FOO is set:以下是检查是否设置$FOO的方法:

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

Actually it can be done this way:其实可以这样实现:

import os

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

Or simply:或者简单地说:

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

For viewing the value in the parameter:查看参数中的值:

print(os.environ['HOME'])

Or:或者:

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

To set the value:要设置值:

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

You can access the environment variables using您可以使用访问环境变量

import os
print os.environ

Try to see the content of the PYTHONPATH or PYTHONHOME environment variables.尝试查看 PYTHONPATH 或 PYTHONHOME 环境变量的内容。 Maybe this will be helpful for your second question.也许这对您的第二个问题有帮助。

As for the environment variables:至于环境变量:

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

That will print all of the environment variables along with their values.这将打印所有环境变量及其值。

Import the os module:导入os模块:

import os

To get an environment variable:获取环境变量:

os.environ.get('Env_var')

To set an environment variable:设置环境变量:

# Set environment variables
os.environ['Env_var'] = 'Some Value'

If you are planning to use the code in a production web application code, using any web framework like Django and Flask , use projects like envparse .如果您打算在生产 Web 应用程序代码中使用代码,使用任何 Web 框架(如DjangoFlask ),请使用项目(如envparse) Using it, you can read the value as your defined type.使用它,您可以将值读取为您定义的类型。

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)

NOTE: kennethreitz's autoenv is a recommended tool for making project-specific environment variables.注意:kennethreitz 的autoenv是推荐用于制作项目特定环境变量的工具。 For those who are using autoenv , please note to keep the .env file private (inaccessible to public).对于使用autoenv的用户,请注意将.env文件保密(公众无法访问)。

There are also a number of great libraries.还有很多很棒的图书馆。 Envs , for example, will allow you to parse objects out of your environment variables, which is rad.例如, Envs将允许您从环境变量(即 rad)中解析对象。 For example:例如:

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

You can also try this:你也可以试试这个:

First, install python-decouple一、安装python-decouple

pip install python-decouple

Import it in your file将其导入您的文件中

from decouple import config

Then get the environment variable然后获取环境变量

SECRET_KEY=config('SECRET_KEY')

Read more about the Python library here .在此处阅读有关 Python 库的更多信息。

Edited - October 2021已编辑 - 2021 年 10 月

Following @Peter's comment, here's how you can test it:在@Peter 的评论之后,您可以通过以下方式对其进行测试:

main.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

If this is true ... It's 1500x faster to use a dict() instead of accessing environ directly.如果这是真的……使用dict()而不是直接访问environ要快 1500 倍。


A performance-driven approach - calling environ is expensive, so it's better to call it once and save it to a dictionary.一种性能驱动的方法 - 调用environ的成本很高,因此最好调用一次并将其保存到字典中。 Full example:完整示例:

from os import environ


# Slower
print(environ["USER"], environ["NAME"])

# Faster
env_dict = dict(environ)
print(env_dict["USER"], env_dict["NAME"])

PS- if you worry about exposing private environment variables, then sanitize env_dict after the assignment. PS-如果您担心暴露私有环境变量,请在分配后清理env_dict

For Django, see Django-environ .对于 Django,请参阅Django-environ

$ pip install django-environ

import environ

env = environ.Env(
    # set casting, default value
    DEBUG=(bool, False)
)
# reading .env file
environ.Env.read_env()

# False if not in os.environ
DEBUG = env('DEBUG')

# Raises Django's ImproperlyConfigured exception if SECRET_KEY not in os.environ
SECRET_KEY = env('SECRET_KEY')

You should first import os using您应该首先使用导入 os

import os

and then actually print the environment variable value然后实际打印环境变量值

print(os.environ['yourvariable'])

of course, replace yourvariable as the variable you want to access.当然,将 yourvariable 替换为您要访问的变量。

The tricky part of using nested for-loops in one-liners is that you have to use list comprehension.在单行中使用嵌套for 循环的棘手部分是您必须使用列表推导。 So in order to print all your environment variables, without having to import a foreign library, you can use:因此,为了打印所有环境变量,而不必导入外部库,您可以使用:

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

.env File .env 文件

Here is my .env file (I changed multiple characters in each key to prevent people hacking my accounts).这是我的 .env 文件(我更改了每个键中的多个字符以防止人们入侵我的帐户)。

SECRET_KEY=6g18169690e33af0cb10f3eb6b3cb36cb448b7d31f751cde
AWS_SECRET_ACCESS_KEY=18df6c6e95ab3832c5d09486779dcb1466ebbb12b141a0c4
DATABASE_URL='postgres://drjpczkqhnuvkc:f0ba6afd133c53913a4df103187b2a34c14234e7ae4b644952534c4dba74352d@ec2-54-146-4-66.compute-1.amazonaws.com:5432/ddnl5mnb76cne4'
AWS_ACCESS_KEY_ID=AKIBUGFPPLQFTFVDVIFE
DISABLE_COLLECTSTATIC=1
EMAIL_HOST_PASSWORD=COMING SOON
MAILCHIMP_API_KEY=a9782cc1adcd8160907ab76064411efe-us17
MAILCHIMP_EMAIL_LIST_ID=5a6a2c63b7
STRIPE_PUB_KEY=pk_test_51HEF86ARPAz7urwyGw9xwLkgbgfCYT48LttlwjEkb88I7Ljb5soBtuKXBaPiKfuu0Cx2BzIowR3jJFkC8ybFBAEf00DFY46tB8
STRIPE_SECRET_KEY=sk_test_19HEF55BCEAz7urwytx7tO3QCxV4R8DEFXbqj6esg7OKuybiSTI8iJD8mmJUQpg4RKENxuS04DKOCzYHpDkAjUttO00LOmsT5Eg

settings设置

I was told my data was corrupted.有人告诉我我的数据已损坏。 I was struggling to work out what was going on.我正在努力弄清楚发生了什么。 I had a suspicion the values from .env were not being passed into my settings file.我怀疑 .env 中的值没有传递到我的设置文件中。

print(os.environ.get('AWS_SECRET_ACCESS_KEY'))
print(os.environ.get('AWS_ACCESS_KEY_ID'))
print(os.environ.get('AWS_SECRET_ACCESS_KEY'))
print(os.environ.get('DATABASE_URL'))
print(os.environ.get('SECRET_KEY'))
print(os.environ.get('DISABLE_COLLECTSTATIC'))
print(os.environ.get('EMAIL_HOST_PASSWORD'))
print(os.environ.get('MAILCHIMP_API_KEY'))
print(os.environ.get('MAILCHIMP_EMAIL_LIST_ID'))
print(os.environ.get('STRIPE_PUB_KEY'))
print(os.environ.get('STRIPE_SECRET_KEY'))

The only value being printed correctly was the SECRET_KEY.唯一正确打印的值是 SECRET_KEY。 I reviewed the .env file and for the life of me could not see any reason why the SECRET_KEY was working and nothing else.我查看了 .env 文件,并且在我的一生中看不到 SECRET_KEY 起作用的任何原因,而没有其他原因。

I got everything working eventually by putting this above the print statements.通过将其放在打印语句之上,我最终使一切正常。

from dotenv import load_dotenv   #for python-dotenv method
load_dotenv()                    #for python-dotenv method

And doing和做

pip install -U python-dotenv

I am still not sure why SECRET_KEY was working when all the others were broken.我仍然不确定为什么 SECRET_KEY 在所有其他人都坏了的情况下工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM