简体   繁体   English

Python-asyncore.dispatcher模块错误

[英]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: 我开始学习这个asyncore.dispatcher模块,当我运行第一个示例程序时,它给出如下错误:

Python version 2.6 Python版本2.6

asyncore module is installed and there is also dispatcher class inside it. 安装了asyncore模块,并且内部还有调度程序类。 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 . 您的问题是您将文件命名为asyncore.py It's shadowing the asyncore.py in the python standard lib so the file is importing itself instead of the real one. 它遮盖了python标准库中的asyncore.py ,因此该文件将自己导入,而不是真正的导入。 You want to rename your copy of the file and delete asyncore.pyc in the same directory if it exists. 您想要重命名文件的副本,并在相同目录中删除asyncore.pyc (如果存在)。 Then when you run your file, you'll be importing the asyncore.py from the standard library. 然后,当您运行文件时,您将从标准库中导入asyncore.py

When Python runs the line import asyncore , python looks through the directories in sys.path for a file named asyncore.py . 当Python运行import asyncore行时,python会在sys.path目录中sys.path名为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. 因此,Python会找到您的文件并尝试将其导入。 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. 通常,如果要使用标准模块,则永远不要给文件命名与标准库中的模块相同的名称。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM