【问题标题】:Make method of derived class async使派生类的方法异步
【发布时间】:2019-04-02 08:52:34
【问题描述】:

我必须创建和使用从上游包派生的类(不可修改) 我想要/需要在派生类中添加/修改一个应该是异步的方法,因为我需要在方法中等待 websocket 发送/接收 我试图只是将异步添加到方法中,但我得到消息(来自基类方法)我的方法来自派生类RuntimeWarning: coroutine MyCopyProgressHandler.end was never awaited 有没有办法将派生类方法“转换”为异步?

【问题讨论】:

    标签: python-3.x python-asyncio


    【解决方案1】:

    当您需要将同步方法转换为异步时,您有 several different options。第二个 (run_in_executor) 可能是最简单的一个。

    例如,您可以这样使同步函数requests.get 异步运行:

    import asyncio
    import requests
    from concurrent.futures import ThreadPoolExecutor
    
    
    executor = ThreadPoolExecutor(10)
    
    
    async def get(url):
        loop = asyncio.get_running_loop()
        response = await loop.run_in_executor(
            executor, 
            requests.get, 
            url
        )
        return response.text
    
    
    async def main():
        res = await get('http://httpbin.org/get')
        print(res)
    
    
    asyncio.run(main())
    

    【讨论】:

      猜你喜欢
      • 2013-11-19
      • 1970-01-01
      • 2020-03-24
      • 1970-01-01
      • 1970-01-01
      • 2012-05-31
      • 1970-01-01
      • 2018-10-12
      • 2018-05-16
      相关资源
      最近更新 更多