在调试时可以修改Python代码吗?使用Pydev、PDB等工具

4 投票
2 回答
1609 浏览
提问于 2025-04-19 11:54

假设我正在用Eclipse的PyDev调试代码。

有没有办法在断点下面添加一些新代码... 就是在程序运行时直接修改代码呢?

2 个回答

0

在PDB中,你可以用

p

来计算和打印表达式,用

!

来执行语句:

p expression

Evaluate the expression in the current context and print its value.

[!]statement

Execute the (one-line) statement in the context of the current stack frame. The exclamation point can be omitted unless the first word of the statement resembles a debugger command. To set a global variable, you can prefix the assignment command with a global command on the same line, e.g.:

(Pdb) global list_options; list_options = ['-l']
(Pdb)

文档链接:https://docs.python.org/2/library/pdb.html

至于如何在PyDev中做到这一点,我不太使用PyDev,所以不太确定;不过这个功能应该在任何基于BDB的调试器中都能找到(我相信PyDev也是基于BDB的?)。

1

我在GitHub上发现了一个有趣的项目:pyrasite

这个项目可以把代码注入到正在运行的Python程序中。你可以在这里了解更多:http://pyrasite.com

撰写回答