Weird select error in python
-
05-07-2021 - |
Question
Ok, so I have Python 2.5 and Windows XP. I was using select.select with a socket object. I tried it again and again, but whenever I run it, the thread it is in gives me an error like select.error(9, "Bad file descriptor"). The code is something like this:
import socket, select
s = socket.socket()
s.bind((socket.gethostbyname(socket.gethostname()), 1312))
s.listen(5)
inputs = [s]
outputs = []
while True:
r, w, e = select.select(inputs, outputs, inputs)
for sock in r:
if sock is s:
inputs.append(s.accept()[0])
else:
print s
print s.recv(1024)
Any info would be appreciated. Thanks!
Solution
You called
select.select
with no arguments. It should be something like:select.select(inputs, outputs, [])
.In the
else
you need to usesock
, nots
(the server).Once the peer disconnects from a previously connected socket, you should remove it from the
inputs
list. You can know the peer has disconnected ifsock.recv()
returns an empty string or raises asocket.error
exception. If you don't do this, you might end up feeding an invalid socket descriptor toselect.select
, causing the error you talked about.