Non-blocking I/O would block
Production Risk
Expected with non-blocking I/O; use selectors or asyncio instead of bare non-blocking calls.
A subclass of OSError (errno EAGAIN/EWOULDBLOCK) raised when a non-blocking I/O operation would block. The underlying resource is not ready; the operation should be retried later.
- 1Reading or writing a non-blocking socket when no data is available
- 2A pipe or socket set to O_NONBLOCK has no data ready
Non-blocking read on a socket with no data.
import socket
s = socket.socket()
s.setblocking(False)
s.connect_ex(('127.0.0.1', 9999))
s.recv(1024) # Raises BlockingIOError if no dataexpected output
BlockingIOError: [Errno 11] Resource temporarily unavailable
Fix 1
Use select/selectors to wait for readiness
WHEN Working with non-blocking sockets
import selectors
import socket
sel = selectors.DefaultSelector()
sock = socket.socket()
sock.setblocking(False)
sel.register(sock, selectors.EVENT_READ)
events = sel.select(timeout=1.0)
for key, mask in events:
data = key.fileobj.recv(1024)Why this works
selectors.select() blocks until the socket is ready, eliminating BlockingIOError.
Fix 2
Use asyncio for async I/O
WHEN Building async servers or clients
import asyncio
async def handle():
reader, writer = await asyncio.open_connection('host', 8080)
data = await reader.read(1024)Why this works
asyncio wraps non-blocking I/O and handles EAGAIN internally.
import socket s = socket.socket() s.setblocking(False) s.recv(1024) # BlockingIOError: resource temporarily unavailable
import socket
try:
data = sock.recv(4096)
except BlockingIOError:
data = None # no data ready, retry laterimport selectors
sel = selectors.DefaultSelector()
sel.register(sock, selectors.EVENT_READ)
events = sel.select(timeout=1)
for key, _ in events:
data = key.fileobj.recv(4096)✕ Spin in a tight loop retrying on BlockingIOError
Busy-waiting wastes CPU; use select/poll/epoll to wait efficiently.
Python Docs — Built-in Exceptions
Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev