【问题标题】:Asyncio error, An operation was attempted on something that is not a socketAsyncio 错误,尝试对非套接字的操作进行操作
【发布时间】:2015-02-21 06:03:20
【问题描述】:

我目前正在编写当前的玩具代码以尝试理解 asyncio 模块。

import asyncio
import os, sys, traceback
from time import time

os.environ['PYTHONASYNCIODEBUG'] = '1'
print(sys.version)

def timed_fib(n):
    def fib(n):
        return fib(n - 1) + fib(n - 2) if n > 1 else n
    a = time()
    return fib(n), time() - a

def process_input():
    text = sys.stdin.readline()
    n = int(text.strip())
    print('fib({}) = {}'.format(n, timed_fib(n)))


@asyncio.coroutine
def print_hello():
    while True:
        print("{} - Hello world!".format(int(time())))
        yield from asyncio.sleep(3)

def main():
    loop = asyncio.get_event_loop()
    loop.add_reader(sys.stdin, process_input)
    loop.run_until_complete(print_hello())


if __name__ == '__main__':
    main()

但是,尝试运行它会产生下面令人难以置信的神秘回溯。如您所见,调试环境变量设置在上面代码的第五行,但是,回溯仍然非常无用,如下所示:

3.4.3rc1 (v3.4.3rc1:69dd528ca625+, Feb  8 2015, 11:01:19) [MSC v.1600 32 bit (In
tel)]
Traceback (most recent call last):
  File "test.py", line 33, in <module>
    main()
  File "test.py", line 29, in main
    loop.run_until_complete(print_hello())
  File "C:\Python34\lib\asyncio\base_events.py", line 304, in run_until_complete

    self.run_forever()
  File "C:\Python34\lib\asyncio\base_events.py", line 276, in run_forever
    self._run_once()
  File "C:\Python34\lib\asyncio\base_events.py", line 1136, in _run_once
    event_list = self._selector.select(timeout)
  File "C:\Python34\lib\selectors.py", line 314, in select
    r, w, _ = self._select(self._readers, self._writers, [], timeout)
  File "C:\Python34\lib\selectors.py", line 305, in _select
    r, w, x = select.select(r, w, w, timeout)
OSError: [WinError 10038] An operation was attempted on something that is not a
socket

如何访问更有用的回溯,可能是什么问题?如果重要的话,我使用的是 Windows 7。

【问题讨论】:

  • 这不是一个解决方案,但我确实复制了你的代码,运行它,它在 osx python 3.4.2 上运行良好。
  • 这很奇怪。我自己在 Windows 7 上。
  • 我明白了。不幸的是,我刚刚检查了,我仍然有错误,所以...

标签: python windows python-3.x python-asyncio


【解决方案1】:

select() 仅适用于 Windows 上的套接字。

要使用文件描述符,您可以尝试非基于选择的事件循环,code example

if os.name == 'nt':
    loop = asyncio.ProactorEventLoop() # for subprocess' pipes on Windows
    asyncio.set_event_loop(loop)
else:
    loop = asyncio.get_event_loop()

虽然我怀疑它对sys.stdin and asynciocode example 有帮助。

【讨论】:

  • 有趣,谢谢!不幸的是,我刚刚尝试了你的后一个代码示例 - 它给了我File "C:\Python34\lib\asyncio\base_events.py", line 241, in _make_write_pipe_transport raise NotImplementedError NotImplementedError,知道那里有什么问题吗?
  • 第二个代码示例是关于 stdio 和 asyncio 的。你必须自己添加Proactor位。
  • 啊,我明白了。非常感谢!
  • 添加 Proactor 后得到OSError: [WinError 6] The handle is invalid
猜你喜欢
  • 2011-03-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-06
  • 1970-01-01
  • 2018-06-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多