python select.select() on Windows

后端 未结 2 1259
野的像风
野的像风 2021-02-09 22:05

I\'m testing UDP punching using code from here. It works on Linux however reports error on Windows. Here\'s the code snippet where the error occurs:

while True:
         


        
相关标签:
2条回答
  • 2021-02-09 22:13

    As the answer suggests, I create another thread to handle input stream and it works. Here's the modified code:

    sock_send = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    
    def send_msg(sock):
        while True:
            data = sys.stdin.readline()
            sock.sendto(data, target)
    
    def recv_msg(sock):
        while True:
            data, addr = sock.recvfrom(1024)
            sys.stdout.write(data)
    
    Thread(target=send_msg, args=(sock_send,)).start()  
    Thread(target=recv_msg, args=(sockfd,)).start()
    
    0 讨论(0)
  • 2021-02-09 22:14

    Unfortunately, select will not help you to process stdin and network events in one thread, as select can't work with streams on Windows. What you need is a way to read stdin without blocking. You may use:

    1. An extra thread for stdin. That should work fine and be the easiest way to do the job. Python threads support is quite ok if what you need is just waiting for I/O events.
    2. A greenlet-like mechanism like in gevent that patches threads support and most of I/O functions of the standard library to prevent them from blocking the greenlets. There also are libraries like twisted (see the comments) that offer non-blocking file I/O. This way is the most consistent one, but it should require to write the whole application using a style that matches your framework (twisted or gevent, the difference is not significant). However, I suspect twisted wrappers are not capable of async input from stdin on Windows (quite sure they can do that on *nix, as probably they use the same select).
    3. Some other trick. However, most of the possible tricks are rather ugly.
    0 讨论(0)
提交回复
热议问题