文章内容
2018/3/2 9:27:01,作 者: 黄兵
在windows中如何设置os.environ.get('MAIL_PASSWORD')
在Python中,如何设置os.environ.get('MAIL_PASSWORD')的值呢?
使用如下方式输出MyVar的值:
os.getenv('MyVar')参考文档如下:
os.getenv(varname[, value])
Return the value of the environment variable varname if it exists, or value if it doesn’t. value defaults to None.
Availability: most flavors of Unix, Windows
下面是详细实例:
>>> import os
>>> os.environ['MyVar'] = 'Hello World!' # set the environment variable 'MyVar' to contain 'Hello World!'
>>> print os.getenv('MyVar')
Hello World!
>>> print os.getenv('not_existing_variable')
None
>>> print os.getenv('not_existing_variable', 'that variable does not exist')
that variable does not exist
>>> print os.environ['MyVar']
Hello World!
>>> print os.environ['not_existing_variable']
Traceback (most recent call last):
File "", line 1, in ?
File "/usr/lib/python2.4/UserDict.py", line 17, in __getitem__
def __getitem__(self, key): return self.data[key]
KeyError: 'not_existing_variable 如果变量存在,os.environ['MyVar']可以工作。与使用os.getenv的区别在于它返回None(或给定的值),而当变量不存在时,os.environ ['MyValue']给出一个KeyError异常。
参考资料:How to read windows environment variable value in python?
评论列表