Can select() be used with files in Python under Wi

2019-01-15 00:58发布

I am trying to run the following python server under windows:

"""
An echo server that uses select to handle multiple clients at a time.
Entering any line of input at the terminal will exit the server.
"""

import select
import socket
import sys

host = ''
port = 50000
backlog = 5
size = 1024
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((host,port))
server.listen(backlog)
input = [server,sys.stdin]
running = 1
while running:
    inputready,outputready,exceptready = select.select(input,[],[])

    for s in inputready:

        if s == server:
            # handle the server socket
            client, address = server.accept()
            input.append(client)

        elif s == sys.stdin:
            # handle standard input
            junk = sys.stdin.readline()
            running = 0

        else:
            # handle all other sockets
            data = s.recv(size)
            if data:
                s.send(data)
            else:
                s.close()
                input.remove(s)
server.close() 

I get the error message (10038, 'An operation was attempted on something that is not a socket'). This probably relates back to the remark in the python documentation that "File objects on Windows are not acceptable, but sockets are. On Windows, the underlying select() function is provided by the WinSock library, and does not handle file descriptors that don’t originate from WinSock.". On internet there are quite some posts on this topic, but they are either too technical for me or simply not clear. So my question is: is there any way the select() statement in python can be used under windows? Please add a little example or modify my code above. Thanks!

3条回答
Ridiculous、
2楼-- · 2019-01-15 01:17

Of course and the answers given are right... you just have to remove the sys.stdin from the input but still use it in the iteration:

for s in inputready+[sys.stdin]:

查看更多
Evening l夕情丶
3楼-- · 2019-01-15 01:33

Look like it does not like sys.stdin

If you change input to this

input = [server] 

the exception will go away.

This is from the doc

 Note:
    File objects on Windows are not acceptable, but sockets are. On Windows, the
 underlying select() function is provided by the WinSock library, and does not 
handle file descriptors that don’t originate from WinSock.
查看更多
对你真心纯属浪费
4楼-- · 2019-01-15 01:33

I don't know if your code has other problems, but the error you're getting is because of passing input to select.select(), the problem is that it contains sys.stdin which is not a socket. Under Windows, select only works with sockets.

As a side note, input is a python function, it's not a good idea to use it as a variable.

查看更多
登录 后发表回答