debugging 我如何告诉Python脚本暂停调试器连接到进程?

m4pnthwp  于 2023-01-13  发布在  Python
关注(0)|答案(5)|浏览(139)

有没有一种方法可以告诉Python在脚本中的某个点暂停执行,并等待调试器连接到进程?
Python中是否有类似于dot-Net的Debugger.Break()的东西?

w8f9ii69

w8f9ii691#

不同的IDE可以使用不同的方法来连接到进程,但是PyCharm、Eclipse、Visual Studio和VS Code都使用pydevd(VS/VSC通过他们的Python插件ptvsd)来提供他们的进程内调试器实现,因此,我们可以用一段代码来针对这些IDE。
其思想是等待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(Community Edition 2019.1.3)中进行了测试。我启动了脚本,在IDE中使用“Attach to process”选项进行了附加,并且能够成功地附加。然后脚本如预期的那样在breakpoint()处停止。

zzoitvuj

zzoitvuj2#

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

import ipdb
ipdb.set_trace()

直接从控制台进行调试。您也可以使用straight out of the box附带的pdb:

import pdb
pdb.set_trace()
up9lanfz

up9lanfz3#

下面是等待pydevd的另一种方法:

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

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

avkwfej4

avkwfej44#

改进了Timofey Solonin的答案https://stackoverflow.com/a/66841531/324204

# ...

import pydevd
import time
while pydevd.get_global_debugger() is None or not pydevd.get_global_debugger().ready_to_run:
    time.sleep(0.3)
breakpoint() # breaks here

# ...

改进之处在于不使用pydevd.connected,pydevd 2.8版中没有定义它。
请注意,在Linux上,您可能会遇到没有附加到进程的权限的问题。How to solve "ptrace operation not permitted" when trying to attach GDB to a process?

cgyqldqp

cgyqldqp5#

你可以使用我的工具madbg来完成这个任务,把这个代码放到你的程序中:

madbg.set_trace()

此行将阻塞,直到调试器使用以下命令连接:

madbg connect

madbg可以从同一台计算机或通过网络连接,也可以抢先停止进程并附加到该进程。

相关问题