开发者社区 问答 正文

如何打包在该包中导入另一个模块的python模块

我正在创建一个python 3.7.2软件包,然后将其安装在virtualenv内的不同位置,以在应用程序中使用。我的程序包有多个模块,它们之间具有依赖关系(导入)。我无法弄清楚如何正确加载程序包,以便可以使用程序包中的依赖模块。

包目录

root
\- foo # my package
   \- __init__.py # empty or with from .helper_class import HelperClass
   \- helper_class.py
   \- my_class.py # imports helper_class
   setup.py

应用目录

app
\- main.py # from foo.my_class import MyClass
\- venv

当my_class不导入helper_class时,我可以打包,安装和运行main.py。当我在my_class中导入helper_class时,我得到ModuleNotFoundError

$ python main.py
Traceback (most recent call last):
  File "main.py", line 1, in <module>
    from foo.my_class import MyClass
  File "/Users/XXXXXX/tmp/foo/my_class.py", line 1, in <module>
    from helper_class import HelperClass
ModuleNotFoundError: No module named 'helper_class'

我试过一个空的init .py,并且还将.helper_class import HelperClass添加到init .py中。我在整个地方的引用中都添加了.s,但没有爱。

我肯定缺少某些非常明显的东西。

app / main.py

o = MyClass()
print(o.get_att())

foo / my_class.py

from helper_class import HelperClass

class MyClass():
    def __init__(self):
        self.att = 123
    def get_att(self):
        return self.att

foo / helper_class.py

class HelperClass():
    def __init__(self):
        pass

下面的Setup.py(摘自https://github.com/navdeep-G/setup.py)

    name=NAME,
    version=about['__version__'],
    description=DESCRIPTION,
    long_description=long_description,
    long_description_content_type='text/markdown',
    author=AUTHOR,
    author_email=EMAIL,
    python_requires=REQUIRES_PYTHON,
    url=URL,
    packages=['foo', ],
    # packages=find_packages(exclude=["tests", "\*tests", "\*tests.\*, "tests.\*]),
    # If your package is a single module, use this instead of 'packages':
    # py_modules=['mypackage'],

    # entry_points={
    #     'console_scripts': ['mycli=mymodule:cli'],
    # },
    install_requires=REQUIRED,
    extras_require=EXTRAS,
    include_package_data=True,
    license='MIT',
    classifiers=[
        # Trove classifiers
        # Full list: https://pypi.python.org/pypi?%3Aaction=list_classifiers
        'License :: OSI Approved :: MIT License',
        'Programming Language :: Python',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.6',
        'Programming Language :: Python :: Implementation :: CPython',
        'Programming Language :: Python :: Implementation :: PyPy'
    ],
    # $ setup.py publish support.
    # cmdclass={
    #     'upload': UploadCommand,
    # },
)

问题来源:stackoverflow

展开
收起
is大龙 2020-03-24 15:36:12 573 分享 版权
1 条回答
写回答
取消 提交回答
  • 请尝试按以下方式导入它...

    from foo.helper_class import HelperClass
    

    回答来源:stackoverflow

    2020-03-24 15:36:20
    赞同 展开评论