importlib找不到modu

2024-04-25 16:48:24 发布

您现在位置:Python中文网/ 问答频道 /正文

猫测试.py

from importlib import import_module

bar = import_module('bar', package='project')

ls项目/

^{pr2}$

Python测试.py

Traceback (most recent call last):
  File "test.py", line 5, in <module>
    bar = import_module('bar', package='project')
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module
    __import__(name)
ImportError: No module named bar

列出导入的模块(系统模块)不显示任何模块项目。在

我可以使用pythonshell导入bar。在

有什么想法吗?在


Tags: 模块项目infrompyimportprojectpackage
2条回答

吧台前面需要一个圆点。。:-(

bar = import_module('.bar', package='project')

import_lib的文档说明

If the name is specified in relative terms, then the package argument must be specified to the package which is to act as the anchor for resolving the package name (e.g. import_module('..mod', 'pkg.subpkg') will import pkg.mod).

因此,表达式也可以写成

bar = import_module('..bar',package='project.bar')

相关问题 更多 >