Question

I want to create a SocketServer on my mac.

However it seems to be some problem with the packages. When I try this sampling code found here it raises attributeerror.

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()

The error :

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'

I do not know if that has to do that I am running on Mac. My python version is:

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

Solution

Seems like you have SocketServer.py somewhere in python path.

Check using following command:

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

Renaming that file will solve your problem.


UPDATE

Rename the file /Users/ddl449/Projects/visualization/SocketServer.py . If there is /Users/ddl449/Projects/visualization/SocketServer.pyc, remove that file .

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top