如何告诉Python脚本需要调试程序附加到进程?

时间:2016-03-02 15:05:17

标签: python debugging

有没有办法告诉Python停止脚本中某个点的执行并等待调试器附加到进程?

在Python中有类似dot-Net的Debugger.Break()吗?

3 个答案:

答案 0 :(得分:1)

安装ipython and ipdb。之后你可以使用

import ipdb
ipdb.set_trace()

直接从控制台调试。 你也可以使用来自straight out of the box的pdb:

import pdb
pdb.set_trace()

答案 1 :(得分:0)

不同的IDE可以使用不同的方法来附加到进程,但是PyCharm,Eclipse,Visual Studio和VS Code都使用pydevd(VS / VSC通过ptvsd通过其Python插件)提供他们的进程内调试器实现。结果,我们可以用一段代码来定位目标对象。

这个想法是等到pydevd导入后再在断点处停止。

import sys
import threading

from importlib.abc import MetaPathFinder


class NotificationFinder(MetaPathFinder):
    def find_spec(self, fullname, _path, _target=None):
        if 'pydevd' in fullname:
            with t:
                t.notify()

t = threading.Condition()
sys.meta_path.insert(0, NotificationFinder())

with t:
    t.wait()

breakpoint()

由于pydevd创建了__builtins__.breakpoint,因此无论Python版本如何,它都应该起作用。我在PyCharm(社区版2019.1.3)中进行了测试。我启动了脚本,并在IDE中附加了“附加到进程”选项,并能够成功附加该脚本。然后,脚本按预期在breakpoint()处停止。

答案 2 :(得分:0)

这是另一种等待pydevd的方法:

while not (pydevd.connected and get_global_debugger().ready_to_run):
    sleep(0.3)
breakpoint()

在我的设置中,MetaPathFinder 仅在我第一次与 pydevd 连接时触发。使用 while 循环,您应该能够重新连接,因为您不依赖于 pydevd 导入副作用。