问题
Is it possible to await
arbitrary calls to an async
function when inside a Python debugger?
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())
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
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.
回答1:
Seems like there's starting to be more support for this feature since Python 3.8. In particular, look at this issue bpo-37028
If you're still on Python 3.7, maybe aiomonitor could have something that supports this feature to a certain extent.
来源:https://stackoverflow.com/questions/57532678/await-an-async-function-in-python-debugger