How to make non-blocking raw_input when using eventlet.monkey_patch() and why it block everything, even when executed on another thread?

て烟熏妆下的殇ゞ 提交于 2019-12-04 17:22:59

I'd say that there are a couple of things to note here:

  • raw_input isn't patched by eventlet, so its calls are blocking
  • threading is patched by eventlet, so threads are acting as coroutines

One way to workaround this would be to avoid patching threading, so that threads are real threads. To do that, you just need to replace:

eventlet.monkey_patch()

with:

eventlet.monkey_patch(os=True,
                     select=True,
                     socket=True,
                     thread=False,
                     time=True)

Note that when thread is True the following modules are patched: thread, threading, Queue.

Edit: If you want to patch threading and have an asynchronous raw_input, then I suggest the following implementation:

def raw_input(message):
    sys.stdout.write(message)

    select.select([sys.stdin], [], [])
    return sys.stdin.readline()

This will poll sys.stdin to check if it's ready for reading. If that's not the case, it will yield control to eventlet to let other coroutine execute.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!