如何访问环境变量值?

问题:如何访问环境变量值?

我设置了要在我的Python应用程序中访问的环境变量。我如何获得它的价值?

I set an environment variable that I want to access in my Python application. How do I get its value?


回答 0

通过os.environ访问环境变量

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

或者,您可以使用以下命令查看所有环境变量的列表:

os.environ

有时您可能需要查看完整的列表!

# using get will return `None` if a key is not present rather than raise a `KeyError`
print(os.environ.get('KEY_THAT_MIGHT_EXIST'))

# os.getenv is equivalent, and can also give a default value instead of `None`
print(os.getenv('KEY_THAT_MIGHT_EXIST', default_value))

Windows上的Python默认安装C:\Python。如果要在运行python时查找,可以执行以下操作:

import sys
print(sys.prefix)

Environment variables are accessed through os.environ

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

Or you can see a list of all the environment variables using:

os.environ

As sometimes you might need to see a complete list!

# using get will return `None` if a key is not present rather than raise a `KeyError`
print(os.environ.get('KEY_THAT_MIGHT_EXIST'))

# os.getenv is equivalent, and can also give a default value instead of `None`
print(os.getenv('KEY_THAT_MIGHT_EXIST', default_value))

Python default installation on Windows is C:\Python. If you want to find out while running python you can do:

import sys
print(sys.prefix)

回答 1

检查密钥是否存在(返回TrueFalse

'HOME' in os.environ

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

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

/home/username/默认位置在哪里

To check if the key exists (returns True or False)

'HOME' in os.environ

You can also use get() when printing the key; useful if you want to use a default.

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

where /home/username/ is the default


回答 2

最初的问题(第一部分)是“如何在Python中检查环境变量”。

这是检查$ FOO是否设置的方法:

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

The original question (first part) was “how to check environment variables in Python.”

Here’s how to check if $FOO is set:

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

回答 3

您可以使用以下命令访问环境变量

import os
print os.environ

尝试查看PYTHONPATH或PYTHONHOME环境变量的内容,也许这将对您的第二个问题有所帮助。但是,您应该澄清一下。

You can access to the environment variables using

import os
print os.environ

Try to see the content of PYTHONPATH or PYTHONHOME environment variables, maybe this will be helpful for your second question. However you should clarify it.


回答 4

至于环境变量:

import os
print os.environ["HOME"]

恐怕您可能还需要再充实一点,才可以得到一个不错的答案。

As for the environment variables:

import os
print os.environ["HOME"]

I’m afraid you’d have to flesh out your second point a little bit more before a decent answer is possible.


回答 5

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

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

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.


回答 6

实际上,可以这样做:

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'])

要么:

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

设置值:

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

Actually it can be done this away:

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 view the value in the parameter:

print(os.environ['HOME'])

Or:

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

To set the value:

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

回答 7

如果您打算在生产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)

注意:kennethreitz的autoenv是推荐的工具,可用于制作项目特定的环境变量,请注意,正在使用的人autoenv请保持.env文件私有(不可访问)

If you are planning to use the code in a production web application code,
using any web framework like Django/Flask, use projects like 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, please note that those who are using autoenv please keep the .env file private (inaccessible to public)


回答 8

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

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

There’s also a number of great libraries. Envs for example will allow you to parse objects out of your environment variables, which is rad. For example:

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

回答 9

对于django,请参阅(https://github.com/joke2k/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')

For django see (https://github.com/joke2k/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')

回答 10

您也可以尝试

一,安装 python-decouple

pip install python-decouple

将其导入您的文件

from decouple import config

然后获取env变量

SECRET_KEY=config('SECRET_KEY')

在此处阅读有关python库的更多信息

You can also try this

First, install python-decouple

pip install python-decouple

import it in your file

from decouple import config

Then get the env variable

SECRET_KEY=config('SECRET_KEY')

Read more about the python library here