How is the select function used in Python?
In Python, select() is a function used for multiplexing. It can monitor the read and write states of multiple file objects (including sockets) simultaneously. When any of these file objects are ready (either for reading or writing), the select() function will return that file object.
The basic syntax of the select() function is as follows:
read_list, write_list, error_list = select.select(inputs, outputs, exceptions, timeout)
Explanation of parameters:
- input: list of readable objects that need to be monitored.
- outputs: list of writable objects that need to be monitored.
- exceptions: a list of abnormal objects that need to be monitored.
- Timeout: Optional parameter that sets the time limit in seconds (by default, it will block until an object is ready).
Explanation of the return value:
- ready objects in the list of readable objects.
- List of writable objects that are ready to be written.
- ready objects in the list of exceptional objects.
Example usage:
import select
import socket
# 创建套接字并监听
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind(('localhost', 8000))
server_socket.listen(5)
inputs = [server_socket]
while True:
# 使用select函数进行监视
readable, writable, exceptional = select.select(inputs, [], [])
for sock in readable:
if sock is server_socket:
# 有新的连接请求
client_socket, client_address = server_socket.accept()
inputs.append(client_socket)
else:
# 有数据可读
data = sock.recv(1024)
if data:
print('Received:', data.decode())
else:
# 客户端断开连接
sock.close()
inputs.remove(sock)
In the above example, the select() function is used to monitor the readability of socket objects. When a new connection request is received, the new client socket is added to the inputs list. If the client sends data, it is printed out.