直接在 python REPL 中使用 await
Use await in python REPL directly
我想知道是否有一种方法可以直接从 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'}}
>>>
我想知道是否有一种方法可以直接从 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'}}
>>>