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) |
有谁知道如何做到这一点?
如何使用
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()) |
另请阅读有关使用
为什么
因为
如果要异步发出请求,则应为此使用特殊的异步模块,例如