How to empty a socket in python?

If by "flush" you mean throw away any pending incoming data then you can either use select() like you do, or set the socket to nonblocking and read in a loop until you're out of data.

Also note that (from the Linux manpage):

Under Linux, select() may report a socket file descriptor as "ready for reading", while nevertheless a subsequent read blocks. This could for example happen when data has arrived but upon examination has wrong checksum and is discarded. There may be other circumstances in which a file descriptor is spuriously reported as ready. Thus it may be safer to use O_NONBLOCK on sockets that should not block.

Spurious readiness notification for Select System call

And as has been noted by others, "flush" usually refers to output.


Using select.select is good practice, as indicated in the Socket Programming HOWTO. You'll need to set the socket as non-blocking, using sock.setblocking(0).

Just a comment about nomenclature: flush is normally associated with output operations.