Events and file polling in a C extension

Josiah Carlson jcarlson at
Sat Oct 23 23:47:33 CEST 2004

Dirk Thierbach <dthierbach at> wrote:
> Donn Cave <donn at> wrote:
> > Quoth Dirk Thierbach <dthierbach at>:
> > So what would you do after select() returns with I/O ready?  Can
> > the library then read and parse, and return the result?
> Yes.
> > I would stay away from threads unless you have a strong need for
> > concurrency that isn't already satisfied with select/poll.  
> So would I, but at the moment I don't see how, unless Python supports
> some sort of event handling. 

I believe that most languages support event handling in one way or
another. Here is one way...

def handle_event(event):
    if event.typ == 'new_connection':
        #handle a new connection
    elif event.typ == ...

Or, if you want to use something that already has much of this designed
and built for sockets, check out asyncore or asynchat.  Use
asyncore.loop(timeout, 1) to poll the sockets every 1/100th of a second
or so, and you should be good.

> > It seems to me the simplest thing by far would be the arrangement I
> > suggested above,
> Which one? Handling select in the main program? That doesn't work,
> because...
> > Python doesn't come with an event handler model, except when used
> > with say a graphic toolkit - so for example Python/Tk will (I
> > assume) look a lot like Tcl/Tk in this respect.
> ... I am exactly after something that looks like Python/Tk with
> respect to Tk-bindings. I want to create an object, let the main
> program do some bindings on that object, and then the main program
> can go on to do whatever it likes. The object should dispatch any
> events that arrive on the file descriptor by invoking the bindings,
> just like the widget bindings in Python/Tk.

These are not hard to make work reasonably.  They can be hard to do well
and in a general fashion.  If you want a general event-based framework,
give Twisted a look (though it does seem to be a bit more socket related).

> Of course I could create some sort of main loop myself, but that
> seems inelegant and not portable. After all, Python/Tk doesn't
> require you to call some sort of main loop, too.

While I do not develop with Tk, I believe you are incorrect.  Checking
Idle, I notice a call to: root.mainloop(), which seems to be the event
handler loop.

In regards to writing your own main loop; what is so inelegant and not
portable about it?  Having done so more than a dozen times, I would say
that writing your own main loop is usually the way to go, unless you
need to hook into some GUI toolkit or a pre-existing event framework, at
which point you can use the toolkit or framework's event processor to
handle dispatch.

 - Josiah

More information about the Python-list mailing list