关于python:如何解决 ‘_Environ’ object has no attribute ‘has_key’

how to solve AttributeError: '_Environ' object has no attribute 'has_key'

1
2
3
4
5
6
7
8
9
def _is_dev_mode():
    # quick hack to check if the program is running in dev mode.
    # if 'has_key' in os.environ  
    if os.environ.has_key('SERVER_SOFTWARE') \
        or os.environ.has_key('PHP_FCGI_CHILDREN') \
        or 'fcgi' in sys.argv or 'fastcgi' in sys.argv \
        or 'mod_wsgi' in sys.argv:
           return False
    return True

在上述代码中,显示以下错误

1
2
if os.environ.has_key('SERVER_SOFTWARE') \
AttributeError: '_Environ' object has no attribute 'has_key'

我相信你正在使用python 3。在python 2中,字典有一个has_key()方法。在Python3中,正如异常所说,它不再存在。您需要使用in操作符:

1
if 'SERVER_SOFTWARE' in os.environ

这里有一个例子(py3k):

1
2
3
4
5
6
7
8
9
10
11
>>> import os
>>> if 'PROCESSOR_LEVEL' in os.environ: print(os.environ['PROCESSOR_LEVEL'])

6
>>> if os.environ.has_key('PROCESSOR_LEVEL'): print("fail")

Traceback (most recent call last):
  File"<pyshell#18>", line 1, in <module>
    if os.environ.has_key('PROCESSOR_LEVEL'): print("fail")
AttributeError: '_Environ' object has no attribute 'has_key'
>>>