首页 > 解决方案 > 在 VSCode 中调试动态加载的模块

问题描述

我加载一些模块并动态导入类

modules = [ f
    for f in glob.glob(join(dirname(__file__), "*.py"))
    if isfile(f) and not f.endswith('__init__.py')
]
for module in modules:
    with open(module, 'rb') as fp:
        module_name = splitext(basename(module))[0]
        ma = imp.load_module(
            'app.purchase.models.vendors.' + module_name, 
            fp, basename(module), ('.py', 'r', imp.PY_SOURCE))
        classes = { c for c in ma.__dict__.items() 
            if isinstance(c[1], type) and issubclass(c[1], PurchaseOrderVendorBase) }
        for class_pair in classes:
            setattr(self, class_pair[0], class_pair[1])
            if class_pair[0] not in __all__:
                __all__.append(class_pair[0])

如果我以后从这种方式导入的类中调用方法,它可以毫无问题地执行。但是 VSCode 中的逐步调试并没有进入该方法,因为它的来源未知。

它在调用堆栈中的其他一些方法中停止。但是中间方法没有显示在调用堆栈中。所以我有一个调用堆栈:

jobs.py:post_purchase_orders() --> Here I can do step-by-step debugging
|- vendor1.py:post_purchase_order() --> This method isn't treated as a blackbox
   |- vendor1.py:login()
      |- browser.py:get_element_by_id() --> Here step-by-step debugging resumes

但在 VSCode 我只看到这个:

在此处输入图像描述

如何将模块绑定到其源代码文件?

标签: pythonvisual-studio-codevscode-debugger

解决方案


好的,我使用了 rioV8 的建议并修改了模块加载逻辑。代替

        ma = imp.load_module(
            'app.purchase.models.vendors.' + module_name, 
            fp, basename(module), ('.py', 'r', imp.PY_SOURCE))

我已经搞定了:

        ma = imp.load_source(
            __name__ + '.' + module_name, 
            module)

这就是诀窍。


推荐阅读