Skip to main content
 首页 » 编程设计

python之我如何告诉 Python 脚本停止调试器附加到进程

2024年10月24日12cloudgamer

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

有没有类似于 dot-Net 的 Debugger.Break() 的东西在 Python 中?

请您参考如下方法:

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

想法是等到 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() 处停止。