使用Conda构建本地Python包成功但无法导入的问题求助
问题描述
尝试用Miniconda创建本地私有Python包(无需上传至仓库或依赖Git),但完成构建安装后,Python导入时报错:
ModuleNotFoundError: No module named 'mbutils'
文件结构
my_root_folder/ ── mbutils/ ├── __init__.py ├── epoch_utils.py ├── misc_utils.py ├── meta.yaml └── setup.py
关键文件内容
__init__.py
from epoch_utils import EpochUtils from misc_utils import MiscUtils __all__ = ["EpochUtils", "MiscUtils"]
epoch_utils.py(示例片段)
from datetime import datetime from datetime import time import pytz class EpochUtils: tz_utc = pytz.timezone("UTC") tz_local = pytz.timezone("Europe/Berlin") def __init__(self): pass def get_epoch_from_localtime(self, st: str) -> int: # 将本地时区的ISO字符串转换为Epoch时间 return int(self.get_ts_from_string(st).timestamp()) # 其他方法...
meta.yaml
package: name: mbutils version: 1.18 source: path: . build: noarch: False number: 1 script: "{{ PYTHON }} -m pip install . -vv" requirements: host: - python >=3.10,<3.13 - pip - setuptools run: - python >=3.10,<3.13 about: author: MB summary: tools description: utility-package
setup.py
from setuptools import setup, find_packages setup( name = "mbutils", version = "1.18", packages = find_packages(), install_requires = [], author = "Your Name", author_email = "your.email@example.com", description = "A utility package", )
已执行操作
- 环境依赖:Python 3.12、conda-build 24.9.0、pip、setuptools均已安装
- 在
my_root_folder目录执行conda build mbutils,成功生成包mbutils-1.18-py312_1.tar.bz2,无报错 - 执行
conda install --use-local mbutils完成安装,conda list mbutils显示安装成功 - 导入包时触发上述
ModuleNotFoundError
解决方案
1. 确认Python环境匹配
确保导入时使用的Python解释器属于安装了mbutils的conda环境:
- 执行
which python(Linux/macOS)或where python(Windows),查看当前Python路径 - 执行
conda list mbutils,确认该环境下确实存在包记录 - 若路径不匹配,激活目标环境:
conda activate <你的环境名>
2. 修正setup.py的包识别逻辑
当前find_packages()在mbutils子目录下执行时,可能无法正确识别包结构。修改setup.py:
from setuptools import setup, find_packages setup( name = "mbutils", version = "1.18", packages = ["mbutils"], # 替换find_packages(),直接指定包名 install_requires = ["pytz"], # 补充epoch_utils依赖的pytz author = "Your Name", author_email = "your.email@example.com", description = "A utility package", )
3. 完善meta.yaml的构建与依赖配置
- 调整构建脚本,避免pip覆盖conda依赖:
build: noarch: False number: 1 script: "{{ PYTHON }} -m pip install . --no-deps -vv"
- 补充
pytz依赖到主机和运行环境:
requirements: host: - python >=3.10,<3.13 - pip - setuptools - pytz run: - python >=3.10,<3.13 - pytz
4. 重新构建安装
- 清理旧构建产物:
conda build purge - 重新构建包:
conda build mbutils - 强制重装:
conda install --use-local mbutils --force-reinstall
5. 验证包安装路径
检查conda环境的site-packages目录是否存在mbutils:
- 获取环境路径:
conda info --envs,定位目标环境的路径 - 进入
lib/python3.12/site-packages/,确认存在mbutils文件夹和对应的.egg-info文件 - 若不存在,说明构建过程未正确复制文件,需重新检查构建脚本配置
内容的提问来源于stack exchange,提问作者Michael
相关产品推荐
相关产品推荐

