开发者

Python - asyncore.dispatcher module error

I started learning this asyncore.dispatcher module and when I run the first example program it gives the error as per below:

Python version 2.6

asyncore module is installed and there is also dispatcher class inside it. What may be the problem !

Error:

AttributeError: 'module' object has no attribute 'dispatcher'

Example code:

import asyncore, socket

class HTTPClient(asyncore.dispatcher):

    def __init__(self, host, path):
        asyncore.dispatcher.__开发者_如何学编程init__(self)
        self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
        self.connect( (host, 80) )
        self.buffer = 'GET %s HTTP/1.0\r\n\r\n' % path

    def handle_connect(self):
        pass

    def handle_close(self):
        self.close()

    def handle_read(self):
        print self.recv(8192)

    def writable(self):
        return (len(self.buffer) > 0)

    def handle_write(self):
        sent = self.send(self.buffer)
        self.buffer = self.buffer[sent:]

client = HTTPClient('www.python.org', '/')
asyncore.loop()


Your problem is that you named your file asyncore.py. It's shadowing the asyncore.py in the python standard lib so the file is importing itself instead of the real one. You want to rename your copy of the file and delete asyncore.pyc in the same directory if it exists. Then when you run your file, you'll be importing the asyncore.py from the standard library.

When Python runs the line import asyncore, python looks through the directories in sys.path for a file named asyncore.py. The directory of the primary file that's executing is always the first entry in it. So Python finds your file and attempts to import it. As a general rule, you should never give your files the same name as a module from the standard library if you want to use that module.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜