在 VSCode 中调试动态加载的模块

Debug dynamically loaded modules in VSCode

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

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])

如果我以后以这种方式调用导入的方法 class 它会毫无问题地执行。但是 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 中我只看到了这个:

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

好的,我使用了 并修改了模块加载逻辑。而不是

        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)

成功了。