python - 在 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 我只看到这个:
如何将模块绑定到其源代码文件?
解决方案
好的,我使用了 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)
这就是诀窍。
推荐阅读
- html - 行在bootstap4表格内部和上方保持浮动
- python - 尝试缓存 s3 文件
- java - Java中是否有下一个排列?
- reactjs - 如何从 antd 表列中使用 React Router
- c# - 当前上下文中不存在名称“实体”
- python - 在 Pip 虚拟环境中 Pip 安装 SHAP 失败
- reactjs - How to get id of selected Select component in Ant Design
- python - Python groupby 函数对数据表进行重新排序
- python - 展开列表中的列表
- nestjs - 我可以在 Nestjs OpenAPI 中进行多态响应吗?