关于python 3.x:等待方法并使用asyncio将变量分配给返回值?

Await a method and assign a variable to the returned value with asyncio?

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

1
2
3
4
import asyncio
import requests
async def main():
    await r = requests.get(URL)

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

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

r =等待request.get(URL)也不起作用,给出

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

有谁知道如何做到这一点?


如何使用await

await仅可用于等待coroutine-调用通过async def定义的函数返回的特殊对象:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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())

另请阅读有关使用asyncio的答案。

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

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

如果要异步发出请求,则应为此使用特殊的异步模块,例如aiohttp或使用线程将requests包装到协程中。 有关这两个示例,请参见此处的代码段。