Python:如果可用,使用 epoll 的库,回退到 select

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

我想在我的 Python 图书馆中使用 select.epoll()

遗憾的是,epoll 并非随处可用。

我需要一种回退到 select.select() 的方法。

我试图在 pypi 上找到一些东西,但没有找到匹配的包:https://pypi.python.org/pypi?%3Aaction=search&term=epoll&submit=search

我该如何解决这个问题"fallback from epoll to select if epoll is not available"?

Python 3.4引入了selectors module。它提供了一个 DefaultSelector 是 "most efficient implementation available on the current platform".

的别名

这是一个快速使用示例:

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)

您可以找到更多 complete example on the Python documentation

DefaultSelector 将按以下顺序尝试:

  • epool (Linux), kqueue (FreeBSD / NetBSD / OpenBSD / OS X) 或 /dev/poll (Solaris)
  • poll (Unix)
  • select

使用 libevent 怎么样,它包装了所有轮询机制并回退到基于您的平台的最佳可用机制 libevent.org

除了 selectors stdlib,我会选择 uvloop,它建立在 Cython 的 libuv 之上。与libevent/libev相比,这两个没有主动维护python绑定,uvloop更有前途。

这是我的两分钱。根据 documentation,epoll 仅适用于 Linux 2.5.44 及更新版本。使用代码:

import os
if os.uname()[0] != 'Linux' or os.uname()[2] < '2.5.44':
    #use select
else:
    #use epoll

更好的是,我认为上面的代码可以变成一个很好的装饰器,可以在程序中的任何地方使用,returns 正确的函数取决于底层 os。