[requirements.txt]依赖文件生成和使用¶
参考:
Python 依赖库管理:pipreqs、pigar、pip-tools、pipdeptree
为了打包python
程序,需要将其依赖环境写入配置文件requirements.txt
中
简介¶
requirements.txt
是一个文本文件,每行表示一个依赖库以及版本,格式如下:
lib1==0.1.0
lib2==0.2.0
生成¶
可以手写requirements.txt
中的依赖库及其版本,也可以自动生成requirements.txt
文件。有多种方式可以实现自动生成,下面介绍其中两种
pip¶
使用pip
命令可以打包当前环境的python
依赖
$ pip freeze > requirements.txt
pigar¶
使用pip freeze
命令打包的是全局依赖环境,而pigar
仅打包当前目录下python
文件的依赖。安装命令如下:
$ pip install pigar
使用命令如下:
$ pigar
Starting generate requirements ...
The following modules are not found yet:
cv2 referenced from:
py/selectivesearchsegmentation_demo.py: 15
Some of them may not install in local environment.
Try to search PyPI for the missing modules and filter some unnecessary modules? (y/[N]) y
Checking modules on the PyPI...
Writing requirements to "/home/zj/文档/selectivesearch/requirements.txt"
Generate requirements done!
生成的requirements.txt
文件中不仅包括了依赖库,还注明了相应的使用
$ cat requirements.txt
# Requirements automatically generated by pigar.
# https://github.com/damnever/pigar
# py/selectivesearchsegmentation_demo.py: 15
opencv-contrib-python == 4.2.0.32
# py/selectivesearchsegmentation_demo.py: 15
opencv-contrib-python-headless == 4.2.0.32
# py/selectivesearchsegmentation_demo.py: 15
opencv-python == 4.2.0.32
# py/selectivesearchsegmentation_demo.py: 15
opencv-python-aarch64 == 3.3.0.1
# py/selectivesearchsegmentation_demo.py: 15
opencv-python-headless == 4.2.0.32
Note:应该查看requirements.txt
文件,去除有些不存在的库,比如工程目录utils
小结¶
需要结合上述两个工具:
- 从
pip freeze
生成的依赖文件中查询到当前工程使用的python
工具依赖 - 从
pigar
生成的requirements.txt
查询到当前工程中python
文件的库依赖
使用¶
使用如下命令安装python
依赖:
$ pip install -r requirements.txt