【问题标题】:Importing modules with same name导入同名模块
【发布时间】:2018-05-02 19:19:52
【问题描述】:

基本上,我有两个python项目,一个位于myapp/screening下,另一个位于myapp/server下。我目前正在开发server 模块,并希望使用myapp.screening 从screening 导入函数。

我的文件夹结构如下图:

myapp/
    screening/
        screening-env/
        myapp/
            __init__.py
            screening/
                __init__.py
                screening_task.py
                submodule1/
                    # __init__.py and ub module files
                submodule2/
                    # __init__.py and sub module files
                submodule3/
                    # __init__.py and sub module files
        tests/
            # __init__.py and test scripts
        setup.py
    server/
        server-env/
        myapp/
            __init__.py
            server/
                __init__.py
                server_task.py
        tests/
            __init__.py
            server_test.py

我按照answer 构建了我的项目。

我的setup.py基本如下:

from setuptools import setup

setup(
    name='myapp-screening',
    version='0.1.0',
    packages=[
        'myapp.screening',
        'myapp.screening.submodule1',
        'myapp.screening.submodule2',
        'myapp.screening.submodule3'
    ],
)

我激活了我的server-env 并通过导航到myapp/screening/(与setup.py 相同的目录)安装了筛选项目并运行python setup.py develop。

最后,server_test.py 和server_task 都是这样的:

from myapp.screening.screening_test import foo

foo()

当我运行 python -m myapp.server.server_task 或 python -m test.server_test 时,我得到:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'myapp.screening'

如果我正在运行 python -m myapp.server.server_task,则此错误是有意义的,因为本地 myapp 存在并且可能会覆盖已安装的包含 screening 模块的 myapp。

有没有办法使用from myapp.screening.screening_task import foo从screening导入东西?!

【问题讨论】:

    标签: python python-import setuptools setup.py


    【解决方案1】:

    所以,经过更多研究,我发现this similar (in a way) question 导致import python modules with the same name 和How do I create a namespace package in Python?。

    “导入同名模块”的答案没有用,因为它说要重命名一个模块或将项目目录变成一个包。

    另一个问题正是我想要的。它基本上讨论了pkgutil,您可以使用它“附加”模块到给定的命名空间。

    对于某些情况(例如this),我理解并分享一些反对这种技术的意见,但由于它是在here 呈现的,因此有时您需要分离的结构,因此即使您不想要所有东西,也不会将所有东西修补在一起

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-10-29
      • 2011-10-01
      • 2021-05-19
      • 1970-01-01
      • 2014-06-15
      • 2012-09-25
      • 2010-11-16
      • 2020-04-04
      相关资源
      最近更新 更多