我在进行网络编程的时候需要使用到 select 模型,同时如果平台是 Linux 就使用 epoll 模型,所以我需要对 Linux 平台的代码做特殊处理,目前我的代码是这样的:
if is_linux():
self.__fds = {}
self.__epoll = select.epoll()
if is_linux():
conn = self._connection_pool[host]
self.__epoll.register(conn.fileno(), select.EPOLLIN)
self.__fds[conn.fileno()] = conn
if is_linux():
while 1:
events = self.__epoll.poll(1)
else:
while 1:
readable, writeable, exceptional = select.select(conns, [], [])
if conn.close(): # 连接已关闭
if is_linux():
self.__epoll.unregister(conn.fileno())
我是对所有需要用到 epoll 的地方添加了环境判断,如果是 linux 环境就做特殊的处理。 以上代码是可以正常使用的,但是感觉不够优雅,不知道各位有没有什么比较优雅的解决方案🤔