我正在运行 Python 3.6.3,并且在我尝试通过 pip 安装的子目录中有以下模块。/g_plotter setup.py /g_plotter __init__.py g_plotter.py Gparser.py设置文件from setuptools import setupsetup( name='g_plotter', packages=['g_plotter'], include_package_data=True, install_requires=[ 'flask', ],)我在我的容器中安装了该模块形式的 Docker:RUN pip3 install ./g_plotter然后在我的应用程序代码中:import g_plotterprint(dir(g_plotter))哪个输出 server_1 | ['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__path__', '__spec__']所以改用这个导入:from g_plotter import g_plotter结果是server_1 | Traceback (most recent call last):server_1 | File "./g_server.py", line 21, in <module>server_1 | from g_plotter import g_plotterserver_1 | File "/usr/local/lib/python3.7/site-packages/g_plotter/g_plotter.py", line 7, in <module>server_1 | import Gparserserver_1 | ModuleNotFoundError: No module named 'Gparser'当我自己运行子模块(这是一个烧瓶应用程序)时,它可以工作。
1 回答

炎炎设计
TA贡献1808条经验 获得超4个赞
您必须在 python 3 中使用绝对导入,import Gparser不再允许。您可以将其更改为:
from . import Gparser
from g_plotter import Gparser
让你更清楚,我将描述它们是什么意思。
import Gparser
Gparser = load_module()
sys.modules['Gparser'] = Gparser
from g_plotter import Gparser
Gparser = load_module()
sys.modules[Gparser_name] = Gparser
from . import Gparser
package = find_package(__name__) # 'g_plotter'
Gparser_name = package + 'Gparser' # g_plotter.Gparser
Gparser = load_module()
sys.modules[Gparser_name] = Gparser
现在你可以理解了,如果你直接运行g_plotter,实际上__name__是__main__,所以python无法从中找到包。只有在其他模块中导入这个子模块,from . import something才能工作。
添加回答
举报
0/150
提交
取消