poll() 相比 select() 移除了文件描述符數量限制,採用鏈表存儲監控對象,更適合大量連接場景。Python select.poll 對象提供面向對象接口,操作更直觀。
import select
poller = select.poll()
poller.register(fd, eventmask)
fd:整數文件描述符或擁有 fileno() 的對象eventmask:位掩碼組合,常用常量:
select.POLLIN — 可讀(普通數據)select.POLLPRI — 可讀(緊急/帶外數據)select.POLLOUT — 可寫select.POLLERR — 錯誤狀態select.POLLHUP — 掛起/連接斷開select.POLLNVAL — 無效請求(未打開的 fd)events = poller.poll(timeout) # timeout 毫秒,-1 為無限阻塞
# 返回 [(fd, event_mask), ...]
poller.unregister(fd)
#!/usr/bin/env python
import select
BLKSIZE = 8192
READ_EVENTS = select.POLLIN | select.POLLPRI | select.POLLHUP | select.POLLERR
def readwrite(from_fd, to_fd):
data = from_fd.read(BLKSIZE)
if data:
to_fd.write(data)
to_fd.flush()
return len(data)
def copy_with_poll(fd_pairs):
total_bytes = 0
fd_map = {src.fileno(): (src, dst) for src, dst in fd_pairs}
poller = select.poll()
for src, _ in fd_pairs:
poller.register(src, READ_EVENTS)
while True:
ready = poller.poll(1000) # 1秒超時
if not ready:
continue
for fd, event in ready:
src, dst = fd_map[fd]
if event & (select.POLLIN | select.POLLPRI):
bytes_read = readwrite(src, dst)
total_bytes += bytes_read
if bytes_read <= 0:
poller.unregister(fd)
src.close()
dst.close()
elif event & (select.POLLERR | select.POLLHUP):
poller.unregister(fd)
src.close()
dst.close()
# 檢查是否所有源文件已關閉
if not fd_map:
break
return total_bytes
def main():
fd_pairs = [
(open("/etc/fstab", "r"), open("/tmp/fstab.poll", "w")),
(open("/etc/passwd", "r"), open("/tmp/passwd.poll", "w"))
]
try:
total = copy_with_poll(fd_pairs)
print(f"Bytes copied: {total}")
except Exception as e:
print(f"Error: {e}")
if __name__ == "__main__":
main()
fileno() 作為鍵快速查找文件對象對event & MASK 判斷具體事件類型POLLERR/POLLHUP 及時清理資源掌握 poll 能夠在無 epoll 環境下構建高性能網絡服務,是理解異步 I/O 演進的關鍵一環。