2 min read

Python Select Module

The select module provides access to platform-specific I/O monitoring functions. It allows you to wait for I/O completion on multiple file descriptors (like sockets or files) simultaneously. This is known as I/O multiplexing.

Importing the Module

import select

select.select()

The most common function is select(), which is available on most operating systems. It waits until one or more file descriptors are ready for some kind of I/O.

Syntax

readable, writable, exceptional = select.select(rlist, wlist, xlist[, timeout])
  • rlist: Wait until ready for reading.
  • wlist: Wait until ready for writing.
  • xlist: Wait for an "exceptional condition".
  • timeout: Time in seconds to wait (float). If omitted, it blocks until at least one file descriptor is ready.

Example: Monitoring Stdin and Sockets

import select
import socket
import sys

# Create a TCP/IP socket
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.setblocking(0)
server.bind(('localhost', 10000))
server.listen(5)

inputs = [server, sys.stdin]
outputs = []

while inputs:
    readable, writable, exceptional = select.select(inputs, outputs, inputs)

    for s in readable:
        if s is server:
            # A "readable" server socket is ready to accept a connection
            connection, client_address = s.accept()
            connection.setblocking(0)
            inputs.append(connection)
        elif s is sys.stdin:
            # Handle standard input
            print(sys.stdin.readline())
        else:
            data = s.recv(1024)
            if data:
                print(f"Received: {data}")
            else:
                inputs.remove(s)
                s.close()

poll() and epoll()

On Linux and Unix systems, poll() and epoll() are available and are generally more efficient than select() for large numbers of file descriptors.

select.poll()

import select

# Only available on Unix/Linux
if hasattr(select, 'poll'):
    p = select.poll()
    # p.register(fd, eventmask)
    # events = p.poll(timeout)

select.epoll()

Available on Linux 2.5.44 and newer.

import select

# Only available on Linux
if hasattr(select, 'epoll'):
    ep = select.epoll()
    # ep.register(fd, eventmask)
    # events = ep.poll(timeout)

programming/python/python