Skip to main content
 首页 » 编程设计

python之在 python 中将我自己的函数作为 asyncio 函数

2025年05月04日10虾米哥

我想在 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() 是一个常规的同步函数。我已经尝试了 similar post 中建议的第二种方法, --- 一个 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。 如果应用程序的大部分构建在异步库之上,但只有相对较小的部分使用线程池,那很好。