等待Python调试器中的异步函数 [英] Await an async function in Python debugger
问题描述
在Python调试器中是否可以await
任意调用async
函数?
Is it possible to await
arbitrary calls to an async
function when inside a Python debugger?
说我在某些main.py
文件中有以下代码:
Say I have the following code in some main.py
file:
import asyncio
async def bar(x):
return x + 1
async def foo():
import ipdb; ipdb.set_trace()
asyncio.run(foo())
现在,我想测试在调试器中使用某些参数调用bar()
来测试结果.发生以下情况:
Now I want to test calling bar()
with some argument inside the debugger to test the results. The following happens:
$ python3 main.py
> /Users/user/test/main.py(8)foo()
7 import ipdb; ipdb.set_trace()
----> 8 return None
9
ipdb> bar(1)
<coroutine object bar at 0x10404ae60>
main.py:1: RuntimeWarning: coroutine 'bar' was never awaited
import asyncio
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
ipdb> await bar(1)
*** SyntaxError: 'await' outside function
当然,我可以通过在ipdb.set_trace()
上方放置x = await bar(1)
,然后检查结果来解决此问题,但是,当调试器处于活动状态时,我无法尝试实时调用函数.
Of course, I can get around this by having x = await bar(1)
above my ipdb.set_trace()
, and then inspecting the results, but then I can't try calling my functions in real time while the debugger is active.
推荐答案
Seems like there's starting to be more support for this feature since Python 3.8. In particular, look at this issue bpo-37028
如果您仍在使用Python 3.7,也许 aiomonitor 可能支持此功能在一定程度上具有特色.
If you're still on Python 3.7, maybe aiomonitor could have something that supports this feature to a certain extent.
这篇关于等待Python调试器中的异步函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!