在Debian上调试Python代码,可以使用以下几种方法:
pdb
进行调试pdb
是Python的内置调试器,适用于命令行环境。以下是一个简单的示例:
import pdb
def buggy_function(x):
result = x * 2
pdb.set_trace() # 手动插入断点
return result + 5
python -m pdb buggy_script.py
pdb
的基本命令:l
(list):查看当前代码上下文n
(next):执行下一行(不进入函数)s
(step):进入函数内部c
(continue):继续执行直到下一个断点b
(break):设置断点p
(print):打印变量值pp
(pretty print):美化打印(如字典)w
(where):显示当前调用堆栈q
(quit):退出调试器对于大型项目和复杂逻辑,推荐使用集成开发环境(IDE)的图形调试器,如 PyCharm 或 Visual Studio Code。
aiomonitor
调试异步代码对于异步编程,可以使用 aiomonitor
实时监控事件循环和活动任务。
aiomonitor
:pip install aiomonitor
import asyncio
import aiomonitor
async def main():
with aiomonitor.start_monitor():
task1 = asyncio.create_task(worker("Task1"))
task2 = asyncio.create_task(worker("Task2"))
await asyncio.gather(task1, task2)
asyncio.run(main())
telnet localhost 50101
在 REPL 中,键入 to view all running tasks
查看所有运行的任务。
logging
模块记录关键状态。通过这些方法和工具,可以有效地在Debian上调试Python代码,无论是简单的命令行程序还是复杂的异步应用。