加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > Windows > 正文

Windows上的python select.select()

发布时间:2020-12-14 04:38:38 所属栏目:Windows 来源:网络整理
导读:我正在使用 here中的代码测试UDP打孔.它可以在Linux上运行,但在Windows上报告错误.这是发生错误的代码片段: while True: rfds,_,_ = select([0,sockfd],[],[]) # sockfd is a socket if 0 in rfds: data = sys.stdin.readline() if not data: break sockfd.
我正在使用 here中的代码测试UDP打孔.它可以在Linux上运行,但在Windows上报告错误.这是发生错误的代码片段:

while True:
    rfds,_,_ = select([0,sockfd],[],[])  # sockfd is a socket
    if 0 in rfds:
        data = sys.stdin.readline()
        if not data:
            break
        sockfd.sendto(data,target)
    elif sockfd in rfds:
        data,addr = sockfd.recvfrom(1024)
        sys.stdout.write(data)

和错误消息:

Traceback (most recent call last):
  File "udp_punch_client.py",line 64,in <module>
    main()
  File "udp_punch_client.py",line 50,in main
    rfds,[])
select.error: (10038,'')

我知道这个错误与Windows上的select实现有一些关系,每个人都引用这个:

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.

所以我有两个问题:

> [0,sockfd]中的0是什么意思?这是一种经常使用的技术吗?
>如果select仅适用于Windows上的套接字,如何使代码与Windows兼容?

谢谢.

解决方法

不幸的是,select不会帮助你在一个线程中处理stdin和网络事件,因为select不能用于Windows上的流.你需要的是一种无阻塞地读取stdin的方法.你可以使用:

> stdin的额外线程.这应该工作正常,是最简单的工作方式.如果您需要的只是等待I / O事件,Python线程支持是完全可以的.
>类似greenlet的机制,如gevent,修补线程支持和标准库的大多数I / O功能,以防止它们阻塞greenlet.还有像twisted(参见注释)这样的库提供非阻塞文件I / O.这种方式是最一致的,但它应该要求使用与您的框架匹配的样式来编写整个应用程序(扭曲或gevent,差异并不重要).但是,我怀疑扭曲的包装器不能从Windows上的stdin进行异步输入(很确定它们可以在* nix上执行此操作,因为它们可能使用相同的选择).>其他一些技巧.然而,大多数可能的技巧都相当丑陋.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读