Skip to content

[requirements.txt]依赖文件生成和使用

为了打包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

还可以使用命令去除引用注释和比较运算符([==, ~=, >=]

$  pigar -o ">=" --without-referenced-comments

小结

需要结合上述两个工具:

  1. pip freeze生成的依赖文件中查询到当前工程使用的python工具依赖
  2. pigar生成的requirements.txt查询到当前工程中python文件的库依赖

使用

使用如下命令安装python依赖:

$ pip install -r requirements.txt

相关阅读