【问题标题】:Python package installed but content from __init__ isn't importable已安装 Python 包,但来自 __init__ 的内容不可导入
【发布时间】:2020-07-06 10:09:06
【问题描述】:

我的包结构如下:

module_installer/   
|-- module_installer
|   `-- __init__.py 
`-- setup.py        

setup.py

from setuptools import setup                             
setup(name='module_installer')

module_installer/__init__.py

class ImportMe():
    pass         

在包的“根目录”中,ImportMe 类是可导入的:

module_installer$ tree --charset=ASCI
|-- module_installer
|   `-- __init__.py
`-- setup.py
python -c "from module_installer import ImportMe"
# This makes sense. The current dir is in python path and the `module_installer` has `__init__.py.

但是,如果我安装它并尝试从不同的目录运行它会失败:

module_installer$ pip install .
module_installer$ cd /some_other_dir
some_other_dir$ python -c "from module_installer import ImportMe"
Traceback (most recent call last):
  File "<string>", line 1, in <module>
ImportError: cannot import name 'ImportMe' from 'module_installer' (unknown location)

grepping pip freeze for module-installer 显示软件包安装成功。

探索文件包不显示已安装的包:

$ pip show -f module-installer
...
Location: /home/user/Envs/se_ena/lib/python3.7/site-packages
...
Files:
  module_installer-0.0.0.dist-info/INSTALLER
  module_installer-0.0.0.dist-info/METADATA
  module_installer-0.0.0.dist-info/RECORD
  module_installer-0.0.0.dist-info/WHEEL
  module_installer-0.0.0.dist-info/top_level.txt
# No traces of module_installer/__init__.py?

__init__.py 是否安装正确且类不可导入?

【问题讨论】:

  • 您的PYTHONPATH 是什么,module_installer 目录具体在哪里?
  • @JohnGordon PYTHONPATH 确实包含/home/user/Envs/se_ena/lib/python3.7/site-packagesmodule_installer 是我的主目录。
  • 修改PYTHONPATH(或sys.path)几乎没有充分的理由。我建议尽量避免做这样的事情,几乎总是有一个更明智的解决方案。

标签: python python-3.x setuptools


【解决方案1】:

在我看来,setup.py 中的 setuptools.setup 函数调用缺少包列表作为 packages 参数的参数。

setup.py:

setup(
    # ...
    packages=['module_installer'],
    # ...
)

为避免手动列出软件包,setuptools 提供了以下实用功能:

【讨论】:

  • 使用 find_packages() 不必键入名称,并且如果您添加更多包,则可以保证未来。
  • @TheMeaningfulEngineer 这有助于回答问题吗?
猜你喜欢
  • 2021-09-26
  • 2020-12-02
  • 2023-01-08
  • 1970-01-01
  • 2019-10-07
  • 2017-05-21
  • 2015-08-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多