首页 > 解决方案 > 已安装 Python 包,但来自 __init__ 的内容不可导入

问题描述

我有以下包结构:

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

安装程序.py

from setuptools import setup                             
setup(name='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 freezeformodule-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正确安装并且类不可导入吗?

标签: pythonpython-3.xsetuptools

解决方案


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

setup.py

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

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


推荐阅读