如何从Python访问环境变量?

时间:2022-03-29 23:25:35

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

我设置了一个要在Python应用程序中访问的环境变量。如何得到这个值?

10 个解决方案

#1


1880  

Environment variables are accessed through os.environ

通过os. Environment访问环境变量

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:

Python在Windows上的默认安装是C:\Python。如果你想在运行python时找到答案,你可以:

import sys
print(sys.prefix)

#2


129  

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

检查键是否存在(返回True/False)

"HOME" in os.environ

or (removed from python 3.x)

或(从python 3.x中删除)

os.environ.has_key("HOME")

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

您还可以在打印密钥时使用get();如果您想使用默认值,这是很有用的。(适用于python 2.7.3)

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

where /home/username/ is the default

默认的/home/username/在哪里

#3


32  

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

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

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)

#4


20  

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.

尝试查看PYTHONPATH或PYTHONHOME环境变量的内容,这可能对您的第二个问题有帮助。但是你应该澄清它。

#5


11  

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.

恐怕你得再多补充一点才能找到一个合适的答案。

#6


9  

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.

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

#7


6  

In Python 3:

在Python 3:

#!/usr/bin/python3
import os
for param in os.environ.keys():
    print("%s: %s " % (param, os.environ[param]))

#8


6  

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.

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

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)

注意:kennethreitz的autoenv是创建项目特定环境变量的推荐工具,请注意使用autoenv的用户请将.env文件保持为私有(无法公开)

#9


1  

Here is a one-line option assuming import os has been done:

假设导入操作系统已经完成,这里有一个单行选项:

for key in os.environ: print(key,':',os.environ[key])

or with formatting:

或与格式:

for key in os.environ: print('{:>30} {:<4} {:}'.format(key,':',os.environ[key]))

#10


-2  

Actualy may be this away:

实际上可能是这样的:

import os

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

Or simplely:

或简单:

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'

#1


1880  

Environment variables are accessed through os.environ

通过os. Environment访问环境变量

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:

Python在Windows上的默认安装是C:\Python。如果你想在运行python时找到答案,你可以:

import sys
print(sys.prefix)

#2


129  

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

检查键是否存在(返回True/False)

"HOME" in os.environ

or (removed from python 3.x)

或(从python 3.x中删除)

os.environ.has_key("HOME")

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

您还可以在打印密钥时使用get();如果您想使用默认值,这是很有用的。(适用于python 2.7.3)

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

where /home/username/ is the default

默认的/home/username/在哪里

#3


32  

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

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

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)

#4


20  

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.

尝试查看PYTHONPATH或PYTHONHOME环境变量的内容,这可能对您的第二个问题有帮助。但是你应该澄清它。

#5


11  

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.

恐怕你得再多补充一点才能找到一个合适的答案。

#6


9  

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.

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

#7


6  

In Python 3:

在Python 3:

#!/usr/bin/python3
import os
for param in os.environ.keys():
    print("%s: %s " % (param, os.environ[param]))

#8


6  

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.

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

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)

注意:kennethreitz的autoenv是创建项目特定环境变量的推荐工具,请注意使用autoenv的用户请将.env文件保持为私有(无法公开)

#9


1  

Here is a one-line option assuming import os has been done:

假设导入操作系统已经完成,这里有一个单行选项:

for key in os.environ: print(key,':',os.environ[key])

or with formatting:

或与格式:

for key in os.environ: print('{:>30} {:<4} {:}'.format(key,':',os.environ[key]))

#10


-2  

Actualy may be this away:

实际上可能是这样的:

import os

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

Or simplely:

或简单:

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'