pyasyncore library
pyasyncore is a compatibility library that re-introduces the `asyncore` module, which was removed from the Python standard library in version 3.12. It allows existing codebases that rely on `asyncore` to continue functioning on Python 3.12 and later. The current version is 1.0.5, with releases typically tied to Python version compatibility or critical bug fixes.
Warnings
- breaking The `asyncore` module was removed from the Python standard library starting with Python 3.12. Code relying on `import asyncore` will raise an `ImportError` on Python 3.12 and later.
- gotcha `asyncore` is a legacy module. While `pyasyncore` provides compatibility for older code, for new asynchronous application development, Python's `asyncio` module is the modern and recommended approach.
- gotcha `pyasyncore` is specifically intended to provide `asyncore` for Python 3.12 and newer. Installing it on older Python versions (where `asyncore` is still part of the standard library) may lead to shadowing the built-in module, potentially causing subtle behavioral differences or confusion.
Install
-
pip install pyasyncore
Imports
- asyncore
import asyncore
- asynchat
import asynchat
Quickstart
import asyncore
import socket
class EchoHandler(asyncore.dispatcher_with_send):
def handle_read(self):
data = self.recv(8192)
if data:
self.send(data)
class EchoServer(asyncore.dispatcher):
def __init__(self, host, port):
asyncore.dispatcher.__init__(self)
self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
self.set_reuse_addr()
self.bind((host, port))
self.listen(5)
print(f"Echo server listening on {host}:{port}")
def handle_accept(self):
pair = self.accept()
if pair is not None:
sock, addr = pair
print(f"Incoming connection from {repr(addr)}")
handler = EchoHandler(sock)
if __name__ == "__main__":
# Note: asyncore is blocking. For a simple example, it runs forever.
# In a real application, you might run it in a separate thread
# or integrate it with other event loops (though this defeats its purpose).
try:
server = EchoServer('127.0.0.1', 8080)
asyncore.loop()
except KeyboardInterrupt:
print("\nServer stopped.")