在 python 中创建我自己的函数作为 asyncio 函数

Make my own function as asyncio function in python

我想使用 Python 中的 asyncio 模块来实现并行执行请求任务,因为我当前的请求任务是按顺序工作的,这意味着它是阻塞的。

看了Python中asyncio模块的文档,写了一些简单的代码如下,但是并没有像我想的那样。

import asyncio
class Demo(object):

    def demo(self):
        loop = asyncio.get_event_loop()
        tasks = [task1.verison(), task2.verison()]
        result = loop.run_until_complete(asyncio.wait(tasks))
        loop.close()
        print(result)

class Task():
   @asyncio.coroutine
   def version(self):
       print('before')
       result = yield from differenttask.GetVersion() 
       # result = yield from asyncio.sleep(1)
       print('after')

我发现他们给出的所有示例都使用 asyncio 函数来使非阻塞工作,如何使自己的函数作为 asyncio 工作?

我想要实现的是,对于一个任务,它将执行请求并且不等待响应然后切换到下一个任务。当我尝试这样做时:我得到 RuntimeError: Task got bad yield: 'hostname',其中 hostname 是我预期结果中的一项。

正如@AndrewSvetlov 所说,differentask.GetVersion() 是一个常规的同步函数。我已经尝试了 中建议的第二种方法 --- Keep your synchronous implementation of searching...blabla

@asyncio.coroutine
def version(self):
    return (yield from asyncio.get_event_loop().run_in_executor(None, self._proxy.GetVersion()))

还是不行,现在的错误是 Task exception was never retrieved future: <Task finished coro=<Task.version() done, defined at /root/syi.py:34> exception=TypeError("'dict' object is not callable",)>

不知道我理解的对不对,请指教

改为

@asyncio.coroutine
def version(self):
    return (yield from asyncio.get_event_loop()
            .run_in_executor(None, self._proxy.GetVersion))

请注意这里没有调用self._proxy.GetVersion而是将函数的引用传递给循环执行器。

现在 GetVersion() 执行的所有 IO 仍然是同步的,但在线程池中执行。

它可能对您有好处,也可能没有。 如果整个程序使用基于线程池的解决方案,您可能只需要 concurrent.futures.ThreadPool,而不是 asyncio。 如果应用程序的大部分构建在异步库之上,但只有相对较小的部分使用线程池——那很好。