【问题标题】:Await a method and assign a variable to the returned value with asyncio?等待一个方法并使用 asyncio 为返回的值分配一个变量?
【发布时间】:2019-02-14 05:44:27
【问题描述】:

我正在使用带有请求的 asyncio 来尝试制作核心模块异步程序。我在尝试做这样的事情时遇到了困难

import asyncio
import requests
async def main():
    await r = requests.get(URL)

我以为这样会做的是等待get请求完成,然后将返回值放入r中,但是发生了这个错误

  File "prog.py", line 20
    await r = requests.get(URL)
    ^
SyntaxError: can't assign to await expression

r = await requests.get(URL) 似乎也不起作用,给

prog.py:31: RuntimeWarning: coroutine 'coroutine' was never awaited
  coroutine(args)

有人知道怎么做吗?

【问题讨论】:

    标签: python-3.x python-asyncio


    【解决方案1】:

    await如何使用?

    await 只能用于等待coroutine - 调用用async def 定义的函数返回的特殊对象:

    import asyncio
    
    
    async def test():
        return True
    
    
    async def main():
    
        # test() returns coroutine:
        coro = test()
        print(coro)  # <coroutine object test at ...>
    
    
        # we can await for coroutine to get result:
        res = await coro    
        print(res)  # True
    
    
    
    if __name__ ==  '__main__':
        loop = asyncio.get_event_loop()
        loop.run_until_complete(main())
    

    另请阅读 this answer 关于使用 asyncio

    为什么await requests.get(URL) 不起作用?

    因为requests.get 不是协程(它不是用async def 定义的),所以它本质上是常规函数。

    如果您想异步发出请求,您应该为此使用特殊的异步模块,例如 aiohttp,或者使用线程将 requests 包装到协程中。两个示例请参见代码 sn-ps here

    【讨论】:

    • 这正是我所需要的。谢谢!
    猜你喜欢
    • 2017-02-10
    • 1970-01-01
    • 2017-07-02
    • 2012-09-09
    • 1970-01-01
    • 2018-03-05
    • 2014-12-22
    • 2012-09-08
    • 2014-05-17
    相关资源
    最近更新 更多