python配置文件读取环境变量,如何在python中读取Windows环境变量值?

I tried this:

os.environ['MyVar']

But it did not work!

Is there any way suitable for all operating systems?

解决方案

Try using the following:

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

So after testing it:

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

Your method would work too if the environmental variable exists. The difference with using os.getenv is that it returns None (or the given value), while os.environ['MyValue'] gives a KeyError exception when the variable does not exist.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值