直接在python REPL中使用await



我想知道是否有一种方法可以直接从python REPL用await调用async函数?

因此,以以下代码为例:

import aiohttp
import asyncio

async def somefunc():
async with aiohttp.ClientSession() as session:
host_url = 'https://somehost'
async with session.get(host_url) as resp:
response = await resp.json()
return response

我正在寻找的是一种简单的方法来调试类似的功能,基本上我想

>>> result = await somefunc()

我知道可以做到这一点

import asyncio
loop = asyncio.get_event_loop()
loop.run_until_complete(somefunc())

但是使用这种方法,我需要更改somefunc的主体来记录响应的结果,或者使用下面这样的额外异步函数来打印结果

async def result_print():
result = await somefunc()
print(result)
loop = asyncio.get_event_loop()
loop.run_until_complete(result_print())

总结以上内容,我正在寻找一种更方便的方式来等待python REPL中的异步函数,也许是一种允许的自定义REPL实现

>>> result = await somefunc()

或者可能有一种方法可以在我不知道的python默认repl中做到这一点?

如果使用启动REPL,则可以使用您想要的行为

python -m asyncio

我不明白为什么你不能得到响应,它似乎是从loop.run_until_complete(somefunc())返回的

我运行了问题中的代码,只对url进行了一次更改,使用host_url = 'https://httpbin.org/json'

>>> response = loop.run_until_complete(mytest.somefunc())
>>> response
{'slideshow': {'author': 'Yours Truly', 'date': 'date of publication', 'slides': [{'title': 'Wake up to WonderWidgets!', 'type': 'all'}, {'items': ['Why <em>WonderWidgets</em> are great', 'Who <em>buys</em> WonderWidgets'], 'title': 'Overview', 'type': 'all'}], 'title': 'Sample Slide Show'}}
>>> 

最新更新