如何解决AttributeError:'_ Environ'对象没有属性'has_key'

anb*_*iah 7 python eclipse web-services

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
Run Code Online (Sandbox Code Playgroud)

在上面的代码中显示以下错误

if os.environ.has_key('SERVER_SOFTWARE') \
AttributeError: '_Environ' object has no attribute 'has_key'
Run Code Online (Sandbox Code Playgroud)

joa*_*uin 15

我想你正在研究python 3.在Python 2中,字典有一个has_key()方法.在Python 3中,正如例外所述,它不再存在.您需要使用in运算符:

if 'SERVER_SOFTWARE' in os.environ
Run Code Online (Sandbox Code Playgroud)

这里有一个例子(py3k):

>>> 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'
>>> 
Run Code Online (Sandbox Code Playgroud)

  • @avasal不在py3k windows中 (3认同)