安利一个开源库:GitHub - samuelcolvin/python-devtools: Dev tools for python
## 1. 打印调试信息
示例代码:
# pip install asynctor devtools httpx
import asynctor
from devtools import debug
from httpx import AsyncClient
async def main():
async with AsyncClient(follow_redirects=True) as client:
r = await client.get("https://qq.com")
print(r)
debug(r)
if __name__ == "__main__":
asynctor.run(main)
结果如下:
<Response [200 OK]>
demo.py:11 main
r: <Response [200 OK]> (Response)
其中第一行是print(r)的输出,另外两行是debug(r)的输出,可以看到debug会打印更多的信息。
## 2. 打印程序段耗时
# pip install asynctor devtools httpx
import asynctor
from devtools import debug
from httpx import AsyncClient
async def main():
with debug.timer("Let's fetch qq.com"):
async with AsyncClient(follow_redirects=True) as client:
r = await client.get("https://qq.com")
print(r)
debug(r)
if __name__ == "__main__":
asynctor.run(main)
输出如下:
Let's fetch qq.com: 0.375s elapsed
<Response [200 OK]>
demo.py:12 main
r: <Response [200 OK]> (Response)
可以看到输出的信息里,自动加了冒号,并打印出了以秒为单位的程序段耗时