Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Lib to use epoll if available, fallback to select

I would like to use select.epoll() in my Python library.

Unfortunately epoll is not available everywhere.

I need a way to fallback to select.select().

I tried to find something at pypi, but failed to find a matching package: https://pypi.python.org/pypi?%3Aaction=search&term=epoll&submit=search

How could I solve this "fallback from epoll to select if epoll is not available"?

like image 763
guettli Avatar asked Jan 11 '18 09:01

guettli


1 Answers

Python 3.4 introduced the selectors module. It offers a DefaultSelector that is an alias to the "most efficient implementation available on the current platform".

Here's a quick usage example:

sel = selectors.DefaultSelector()

sel.register(fp1, selectors.EVENT_READ)
sel.register(fp2, selectors.EVENT_READ)
sel.register(fp3, selectors.EVENT_READ)

for key, mask in sel.select():
    print(key.fileobj)

You can find a more complete example on the Python documentation.

DefaultSelector will try, in this order:

  • epool (Linux), kqueue (FreeBSD / NetBSD / OpenBSD / OS X) or /dev/poll (Solaris)
  • poll (Unix)
  • select
like image 162
Andrea Corbellini Avatar answered Oct 02 '22 15:10

Andrea Corbellini