Python Asynchronous I/O library (pyasynchio)

This Python library is created to support asynchronous I/O (Input/Output) operations. Unlike most platform-independent asynch I/O libraries, pyasynchio is simple. You do not have to know much about programming and anything about AIO in particular to use pyasynchio. Unlike, for example, famous asyncore library, pyasynchio does not require you to use some object-oriented approaches, implement certain interfaces or do anything similar. However you should understand what file or socket is J, because currently pyasynchio provides I/O only for files and sockets.

Lets move to the code. Here is a simple TCP echo implemented with pyasynchio:

import sys

import socket

import pyasynchio

 

# Create and bind socket

lsock = socket.socket()

lsock.bind((sys.argv[1], int(sys.argv[2])))

lsock.listen(5)

 

# Create apoll object

apoll = pyasynchio.apoll()

# Issue first asynch accept through apoll object

apoll.accept(lsock)

 

while True:

    # poll results from apoll object

    events = apoll.poll()

    # process them one by one

    for evt in events:

        # if operation was accept

        if evt['type'] == 'accept':

            # moreover, if it is successful

            if evt['success']:

                # issue asynchronous read through apoll object

                apoll.recv(evt['accept_socket'], 1024)

                # issue another asynch accept, so that more clients can connect

                apoll.accept(lsock)

        # if operation was recv

        elif evt['type'] == 'recv':

            # if received some data and connection isnt broken (just as recv it presents empty string if client disconnected)

            if evt['success'] and evt['data'] != '':

                # issue asynchronous send to echo data back to client. No need to pick up results of this op

                apoll.send(evt['socket'], evt['data'])

                # issue new recv so we can echo more data

                apoll.recv(evt['socket'], 1024)

# EOF :)

done. Uses built-in python socket handles from socketmodule (and builtin files, if you want file I/O). In fact, pyasynchio.apoll class is just the only class which is currently exported by this library.

If you are interested, you can look into the docs, or download library itself (currently just for Windows 2000/XP/2003 family of OS and MSVC .NET 2003 compiler, however Unix version with full socket I/O support is coming!), and/or participate in mailing list about pyasynchio (at this point any feedback is welcome!).

 

--

Vladimir Sukhoy vladimir dot sukhoy at G mail dot com