select 是 Python 標準庫提供的 I/O 多路復用接口,底層調用系統 select() 系統調用,可同時監控多個文件描述符的可讀/可寫/異常狀態,實現單線程處理多路 I/O。
select.select(rlist, wlist, xlist[, timeout])
rlist:待檢測可讀的文件對象列表wlist:待檢測可寫的文件對象列表xlist:待檢測異常的文件對象列表timeout:超時時間(秒,浮點數),None 表示無限阻塞返回值:三個列表 (rlist_ready, wlist_ready, xlist_ready),包含就緒的文件對象。
#!/usr/bin/env python
import select
BLKSIZE = 8192
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_files(fd_pairs):
"""
fd_pairs: [(from_fd1, to_fd1), (from_fd2, to_fd2), ...]
"""
total_bytes = 0
# 提取所有源文件描述符
read_fds = [pair[0] for pair in fd_pairs]
while True:
# 監控可讀事件
ready_read, _, _ = select.select(read_fds, [], [])
for rfd in ready_read:
# 查找對應的目標文件
for src, dst in fd_pairs:
if src is rfd:
bytes_read = readwrite(src, dst)
total_bytes += bytes_read
if bytes_read <= 0: # EOF
read_fds.remove(rfd)
break
if not read_fds: # 所有文件複製完成
break
return total_bytes
def main():
fd_pairs = [
(open("/etc/fstab", "r"), open("/tmp/fstab.copy", "w")),
(open("/etc/passwd", "r"), open("/tmp/passwd.copy", "w"))
]
try:
total = copy_files(fd_pairs)
print(f"Total bytes copied: {total}")
finally:
for src, dst in fd_pairs:
src.close()
dst.close()
if __name__ == "__main__":
main()
fileno() 方法的對象select 返回就緒列表後,必須循環處理直到無數據,否則下次不會再次通知FD_SETSIZE 限制(通常 1024)| 特性 | select | poll | epoll (Linux) |
|---|---|---|---|
| 最大連接數 | 1024 (典型) | 無硬性限制 | 無硬性限制 |
| 時間複雜度 | O(n) | O(n) | O(1) |
| 觸發模式 | 水平觸發 | 水平觸發 | 邊沿/水平觸發 |
| Python 支援 | 全平台 | Unix/Linux | Linux (select.epoll) |
select 適合連接數較少、跨平台的場景;高併發 Linux 服務器建議使用 epoll 或 asyncio 高層抽象。