如何获取setup.py中install_requires包列表?求版本差异检测工具
获取本地包setup.py的install_requires及版本差异检查方法
一、提取setup.py中的install_requires列表
要实现类似pip show pkgname | grep -i requires的本地包依赖查询效果,同时保留版本约束,有几种简单方法:
1. 用Python脚本直接解析
写一个简短的脚本读取setup.py的配置,无需生成额外文件:
# 保存为get_install_requires.py from setuptools import setup # 执行setup.py并提取配置参数 setup_config = {} with open('setup.py', 'r') as f: exec(f.read(), {}, setup_config) # 打印带版本约束的依赖列表 for req in setup_config.get('install_requires', []): print(req)
执行脚本即可得到结果:
python get_install_requires.py
2. 利用setuptools的egg_info命令
运行以下命令生成egg-info目录,其中的requires.txt文件直接包含install_requires的内容:
python setup.py egg_info
查看依赖列表:
cat your_package_name.egg-info/requires.txt
注:此方法会生成临时文件,可在查看后删除。
二、检查setup.py与requirements.txt的版本差异
如果要对比两者的版本约束差异,有几种实用方案:
1. 用pip-tools生成对比文件
pip-tools可以从setup.py生成标准化的requirements文件,再与现有文件对比:
首先安装工具:
pip install pip-tools
从setup.py生成requirements文件:
pip-compile setup.py --output-file setup-generated-requirements.txt
用diff工具对比版本差异:
diff setup-generated-requirements.txt requirements.txt
2. 自定义脚本快速对比
不想用第三方工具的话,可手动整理后对比:
- 用上述脚本提取
setup.py的依赖并保存为setup-reqs.txt - 清理
requirements.txt的注释和空行:
grep -v '^#' requirements.txt | grep -v '^$' > cleaned-reqs.txt
- 对比两个文件:
diff setup-reqs.txt cleaned-reqs.txt
3. 使用专门的对比工具
reqcmp可直接对比两个依赖源(包括从setup.py读取的依赖),输出详细差异报告:
pip install reqcmp reqcmp setup.py requirements.txt
内容的提问来源于stack exchange,提问作者thebjorn
相关产品推荐
相关产品推荐

