当我从空闲状态导入 `http.server` 时,它可以工作,但是当我 运行 一个具有 `import http.server` 的 python 文件时出现错误

When I am importing `http.server` from the idle it works, but when I run a python file having `import http.server` there is an error

当我使用时:

>>> import http.server

IDLE中没有任何错误。
但是当我使用这段代码时:

import http.server
from http.server import BaseHTTPRequestHandler
from http.server import HTTPServer

def run(server_class = HTTPServer, handler_class = BaseHTTPRequestHandler):
    server_address = ('', 8000)
    httpd=server_class(server_address, handler_class)
    httpd.serve_forever()


run()

出现错误如下:

Traceback (most recent call last):
  File "<frozen importlib._bootstrap>", line 2195, in _find_and_load_unlocked
AttributeError: 'module' object has no attribute '__path__'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/toton/Projects/http.py", line 1, in <module>
    import http.server
  File "/home/toton/Projects/http.py", line 1, in <module>
    import http.server
ImportError: No module named 'http.server'; 'http' is not a package

请帮忙!

您已将文件命名为 http.py,因此它覆盖了原始模块 http

解决

  • 将文件名更改为其他名称
  • 删除 pyc 文件
  • 运行又是节目