萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Python select 實現異步 I/O 多路復用完整教程

select 模塊核心機制

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()

關鍵技術點

  1. 文件對象要求:必須是整數文件描述符或擁有 fileno() 方法的對象
  2. 邊沿觸發特性:select 返回就緒列表後,必須循環處理直到無數據,否則下次不會再次通知
  3. 跨平台差異:Windows 僅支援 socket,Unix/Linux 支援所有文件類型
  4. 性能限制:單進程監控文件描述符數量受 FD_SETSIZE 限制(通常 1024)

select vs poll vs epoll

特性selectpollepoll (Linux)
最大連接數1024 (典型)無硬性限制無硬性限制
時間複雜度O(n)O(n)O(1)
觸發模式水平觸發水平觸發邊沿/水平觸發
Python 支援全平台Unix/LinuxLinux (select.epoll)

select 適合連接數較少、跨平台的場景;高併發 Linux 服務器建議使用 epoll 或 asyncio 高層抽象。

copyright © 萬盛學電腦網 all rights reserved