SocketServer模块无法导入任何模块

3
我想在我的Mac上创建一个SocketServer。
然而,似乎出现了一些包的问题。当我尝试使用这里找到的示例代码时,它会引发属性错误。
import SocketServer

class MyTCPHandler(SocketServer.BaseRequestHandler):
    """
    The RequestHandler class for our server.

    It is instantiated once per connection to the server, and must
    override the handle() method to implement communication to the
    client.
    """

    def handle(self):
        # self.request is the TCP socket connected to the client
        self.data = self.request.recv(1024).strip()
        print "{} wrote:".format(self.client_address[0])
        print self.data
        # just send back the same data, but upper-cased
        self.request.sendall(self.data.upper())

if __name__ == "__main__":
    HOST, PORT = "localhost", 9999

    # Create the server, binding to localhost on port 9999
    server = SocketServer.TCPServer((HOST, PORT), MyTCPHandler)

    # Activate the server; this will keep running until you
    # interrupt the program with Ctrl-C
    server.serve_forever()

这个错误:

Traceback (most recent call last):
  File "/Users/ddl449/Projects/visualization/SocketServer.py", line 1, in <module>
    import SocketServer
  File "/Users/ddl449/Projects/visualization/SocketServer.py", line 3, in <module>
    class MyTCPHandler(SocketServer.BaseRequestHandler):
AttributeError: 'module' object has no attribute 'BaseRequestHandler'

我不知道这是否与我正在使用Mac有关。我的Python版本是:

2.7.5 (v2.7.5:ab05e7dd2788, May 13 2013, 13:18:45) 
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)]

1
为什么不复制整个回溯? - Antti Haapala -- Слава Україні
1
看,当您提供完整的回溯信息时,人们可以立即帮助您。 - Antti Haapala -- Слава Україні
1个回答

6

看起来你的Python路径中某处有 SocketServer.py

使用以下命令进行检查:

python -c "import SocketServer; print(SocketServer.__file__)"

将该文件重命名即可解决问题。


更新

将文件/Users/ddl449/Projects/visualization/SocketServer.py重命名。如果有/Users/ddl449/Projects/visualization/SocketServer.pyc,请删除该文件。


1
可能主文件是 SocketServer.py。 - Antti Haapala -- Слава Україні
谢谢你们两个。是文件名的问题。 - Diolor
我在我的主文件夹中有一个名为SocketServer.pyc的文件,但出于某种原因我不知道它来自哪里。谢谢。 - ioan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接