0

Python wikiから最初の例を実行しようとしましたが、実行しようとすると:

$ python BaseHttpServer.py

エラーAttributeError: 'module' object has no attribute 'BaseHTTPRequestHandler' が表示されます。

Linux Mageia 2 64 ビットの Python 2.7.3 でテストしました。

Traceback (most recent call last):
  File "BaseHTTPServer.py", line 9, in <module>
    import BaseHTTPServer
  File "/home/vanveber/BaseHttpServer/BaseHTTPServer.py", line 14, in <module>
    class MyHandler(BaseHTTPServer.BaseHTTPRequestHandler):
AttributeError: 'module' object has no attribute 'BaseHTTPRequestHandler'

そして、Windows 7 64ビットのPython 2.7.3でそれ

Traceback (most recent call last):
  File "BaseHTTPServer.py", line 11, in <module>
    from BaseHTTPServer import BaseHTTPRequestHandler
  File "C:\BaseHttpServer\BaseHTTPServer.py", line 11, in <module>
    from BaseHTTPServer import BaseHTTPRequestHandler
ImportError: cannot import name BaseHTTPRequestHandler

しかし!

  1. BaseHttpServer は、標準 Python ライブラリのクラスです。
  2. Windows の Python GUIからこのコードを作成して実行すると、正しく動作します。

何が問題で、その理由は?!

4

1 に答える 1

3

Solution: Rename the python file.

Explanation: BaseHTTPServer is a module in the standard library. When you have a python file called BaseHTTPServer.py in your local directory, you will hide the standard library module, and you can no longer import it, because the statement

import BaseHTTPServer

will not import the standard library module, but the local BaseHTTPServer.py module.

于 2012-11-30T10:50:54.810 に答える