![cover](https://img-blog.csdnimg.cn/img_convert/48a3ef3f4588483b90967069e3e02747.png)
在vscode中调试,命令行出现错误信息ModuleNotFoundError: No module named ‘imp‘
VSCode的python扩展会使用debugpy库实现调试功能。在涉及qt组件加载时,debugpy的会尝试加载imp库。而在python3.12及以后的版本中,imp库被importlib取代,因此import imp语句会报错。
在vscode中调试,命令行出现错误信息ModuleNotFoundError: No module named ‘imp’
报错原因
VSCode的python扩展会使用debugpy
库实现调试功能。在涉及qt组件加载时,debugpy
的qt_loaders.py
会尝试加载imp库。而在python3.12及以后的版本中,imp
库被importlib
取代,因此
import imp
语句会报错ModuleNotFoundError
。
解决方法
出现问题代码位于qt_loaders.py
的has_binding
函数定义中:
修改前:
def has_binding(api):
#中间省略
import imp
try:
# importing top level PyQt4/PySide module is ok...
mod = __import__(module_name)
# ...importing submodules is not
imp.find_module('QtCore', mod.__path__)
imp.find_module('QtGui', mod.__path__)
imp.find_module('QtSvg', mod.__path__)
# we can also safely check PySide version
if api == QT_API_PYSIDE:
return check_version(mod.__version__, '1.0.3')
else:
return True
except ImportError:
return False
对症下药,既然在新版python中imp
库不再有效,为了兼容性,先尝试import imp
语句,若无法导入imp
包,则进入catch分支import importlib
,修改代码如下:
def has_binding(api):
#中间省略
try:
import imp
# importing top level PyQt4/PySide module is ok...
mod = __import__(module_name)
# ...importing submodules is not
imp.find_module('QtCore', mod.__path__)
imp.find_module('QtGui', mod.__path__)
imp.find_module('QtSvg', mod.__path__)
# we can also safely check PySide version
if api == QT_API_PYSIDE:
return check_version(mod.__version__, '1.0.3')
else:
return True
except ModuleNotFoundError:
from importlib import machinery
# importing top level PyQt4/PySide module is ok...
mod = __import__(module_name)
# ...importing submodules is not
loader_details = (machinery.ExtensionFileLoader, machinery.EXTENSION_SUFFIXES)
submod_finder = machinery.FileFinder(mod.__path__[0], loader_details)
submod_check = (
submod_finder.find_spec("QtCore") is not None
and submod_finder.find_spec("QtGui") is not None
and submod_finder.find_spec("QtSvg") is not None
)
# we can also safely check PySide version
if api == QT_API_PYSIDE:
return check_version(mod.__version__, '1.0.3') and submod_check
else:
return submod_check
except ImportError:
return False
可能有的同学会问,qt_loaders.py
在哪里?——它的路径在报错信息中已经给出。例如:
C:\Users\XXX.vscode\extensions\ms-python.python-2024.2.1\pythonFiles\lib\python\debugpy_vendored\pydevd\pydev_ipython\qt_loaders.py", line 115, in has_binding
import imp
ModuleNotFoundError: No module named ‘imp’
Backend QtAgg is interactive backend. Turning interactive mode on.
更多推荐
所有评论(0)