猿问

导入后找不到模块

我正在运行 Python 3.6.3,并且在我尝试通过 pip 安装的子目录中有以下模块。


/g_plotter

          setup.py

          /g_plotter

                    __init__.py

                    g_plotter.py

                    Gparser.py

设置文件


from setuptools import setup


setup(

    name='g_plotter',

    packages=['g_plotter'],

    include_package_data=True,

    install_requires=[

        'flask',

    ],

)

我在我的容器中安装了该模块形式的 Docker:


RUN pip3 install ./g_plotter

然后在我的应用程序代码中:


import g_plotter


print(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_plotter

server_1  |   File "/usr/local/lib/python3.7/site-packages/g_plotter/g_plotter.py", line 7, in <module>

server_1  |     import Gparser

server_1  | ModuleNotFoundError: No module named 'Gparser'

当我自己运行子模块(这是一个烧瓶应用程序)时,它可以工作。


慕妹3242003
浏览 199回答 1
1回答

炎炎设计

您必须在 python 3 中使用绝对导入,import Gparser不再允许。您可以将其更改为:from . import Gparserfrom g_plotter import Gparser让你更清楚,我将描述它们是什么意思。import GparserGparser = load_module()sys.modules['Gparser'] = Gparserfrom g_plotter import GparserGparser = load_module()sys.modules[Gparser_name] = Gparserfrom . import Gparserpackage = find_package(__name__)&nbsp; # 'g_plotter'Gparser_name = package + 'Gparser'&nbsp; # g_plotter.GparserGparser = load_module()sys.modules[Gparser_name] = Gparser现在你可以理解了,如果你直接运行g_plotter,实际上__name__是__main__,所以python无法从中找到包。只有在其他模块中导入这个子模块,from . import something才能工作。
随时随地看视频慕课网APP

相关分类

Python
我要回答