How do I access environment variables from Python?

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


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)

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

"HOME" in os.environ

or (removed from 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 )

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

where /home/username/ is the default


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)
链接地址: http://www.djcxy.com/p/4090.html

上一篇: 我怎样才能初始化一个静态地图?

下一篇: 我如何从Python访问环境变量?