【问题标题】:Debug dynamically loaded modules in VSCode在 VSCode 中调试动态加载的模块
【发布时间】:2020-11-26 07:03:40
【问题描述】:

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

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 中我只看到这个:

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

【问题讨论】:

  • 因为你打开文件文件路径的链接不见了,所以必须有一个使用文件路径的load_module方法

标签: python visual-studio-code vscode-debugger


【解决方案1】:

好的,我使用了advice of 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)

这样就成功了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-22
    • 2010-10-20
    • 2010-10-31
    相关资源
    最近更新 更多