pyinstrument
pyinstrument copied to clipboard
`pytinstrument` does not track the call stack of `__aenter__` and `__aexit__`
I am using pyinstrument to track an async code with aiohttp. My purpose is that to analyze why my custom __aexit__() is not called, but there are no record about my custom code whether __aenter__() or __aexit__().
Here is my code named test_aio.py, this is the correct version where I manually call __aenter__ and __aexit__.
import asyncio, aiohttp
class AioHttpSession:
def __init__(self) -> None:
self._session = None
async def __aenter__(self):
if self._session is None:
self._session = await aiohttp.ClientSession().__aenter__()
return self
async def __aexit__(self):
if self._session is None:
raise RuntimeError("session it not initilaized")
await self._session.__aexit__(None, None, None)
async def request(self, url="http://www.baidu.com"):
if self._session is None:
await self.__aenter__()
async with self._session.get(url) as response:
data = await response.text()
print(self._session)
return data
class MyAPP:
def __init__(self) -> None:
self.client = AioHttpSession()
async def fetch(self):
session = await self.client.__aenter__()
try:
resp = await session.request()
return resp
except Exception as e:
if resp is not None:
await resp.release()
await session.__aexit__(None, None, None)
raise
async def main():
app = MyAPP()
tasks = [app.fetch() for _ in range(3)]
res = await asyncio.gather(*tasks)
await app.client.__aexit__()
asyncio.run(main())
And I run pyinstrument with pyinstrument --show-all test_aio.py. But no called information about AioHttpSession.__aenter__() or `aexit().
To track time spent in awaits, you have to start the profiler inside the async task you're interested in. You can't use the command-line style.