如何在安装Python Wheel时通过Pip选项生成配置模块
实现pip install时传入自定义参数并修改配置文件
问题描述
需求:执行
pip install时传入自定义参数(如--cfg_dir),在安装Python Wheel包过程中,将该参数值写入项目的conf.py文件(例如写入CONF_DIR="/path/to/cfg_dir")。
项目结构:top_repository/ |/setup.py |/requirements.txt |/my_proj |/__init__.py |/__main__.py |/_version.py |/conf.py当前
setup.py代码:from setuptools import setup, find_packages from distutils.util import convert_path def get_requirements(): with open('requirements.txt') as fp: return fp.read() def get_version(): st = {} version_file = convert_path('my_proj/_version.py') with open(version_file) as f: exec(f.read(), st) return st['_version'] setup(name='my_proj', version=get_version(), description='My Proj', packages=find_packages(), zip_safe=False)环境:Python 3.9.18、setuptools 53.0.0,通过
python setup.py bdist_wheel生成wheel包,暂未找到可行方案。
解决方案
1. 自定义Install命令类
在setup.py中实现继承自setuptools.command.install.install的自定义命令类,用于捕获--cfg_dir参数,并在安装完成后修改conf.py文件。
2. 更新setup.py代码
替换原setup.py为以下内容:
from setuptools import setup, find_packages from setuptools.command.install import install from distutils.util import convert_path import os def get_requirements(): with open('requirements.txt') as fp: return fp.read() def get_version(): st = {} version_file = convert_path('my_proj/_version.py') with open(version_file) as f: exec(f.read(), st) return st['_version'] class CustomInstall(install): # 添加自定义参数选项 user_options = install.user_options + [ ('cfg_dir=', None, 'Path to configuration directory'), ] def initialize_options(self): install.initialize_options(self) self.cfg_dir = None # 初始化参数默认值 def finalize_options(self): install.finalize_options(self) def run(self): # 先执行默认安装流程 install.run(self) # 若传入了cfg_dir参数,修改conf.py if self.cfg_dir: # 定位安装后的conf.py路径 conf_path = os.path.join(self.install_lib, 'my_proj', 'conf.py') # 读取原有内容并替换/添加CONF_DIR配置 with open(conf_path, 'r') as f: lines = f.readlines() found = False with open(conf_path, 'w') as f: for line in lines: if line.startswith('CONF_DIR'): f.write(f'CONF_DIR = "{self.cfg_dir}"\n') found = True else: f.write(line) # 若原有文件无CONF_DIR,追加写入 if not found: f.write(f'\nCONF_DIR = "{self.cfg_dir}"\n') setup(name='my_proj', version=get_version(), description='My Proj', packages=find_packages(), zip_safe=False, # 注册自定义安装命令 cmdclass={ 'install': CustomInstall, })
3. 准备conf.py模板
确保my_proj/conf.py初始包含CONF_DIR配置项(或留空,由安装脚本自动添加):
# 项目配置文件 CONF_DIR = "" # 其他配置项...
4. 生成并安装wheel包
- 生成wheel包:
python setup.py bdist_wheel - 带自定义参数安装:
pip install dist/my_proj-<version>-py3-none-any.whl --install-option="--cfg_dir=/path/to/your/cfg_dir"
注意事项
- 该方案仅适用于本地wheel包/源码安装,PyPI上的预编译wheel包无法在安装时动态修改文件。
- 使用
pip install .(源码安装)时,同样可以通过--install-option传递参数。 - 需保证安装过程对目标
conf.py文件有写入权限,避免修改失败。
内容的提问来源于stack exchange,提问作者lrbbs
相关产品推荐
相关产品推荐

