0%

关于Python依赖包文件requirements

Python项目中的依赖包一般通过 requirements.txt 来记录。

问题

一般情况下我们都是通过命令 pip freeze > requirements.txt 来生成项目依赖文件:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
amqp==2.4.2
aniso8601==6.0.0
billiard==3.5.0.5
celery==4.2.2
certifi==2019.3.9
chardet==3.0.4
Click==7.0
Flask==1.0.2
Flask-RESTful==0.3.7
Flask-Script==2.0.6
idna==2.8
itsdangerous==1.1.0
Jinja2==2.10
kombu==4.3.0
MarkupSafe==1.1.1
pytz==2018.9
requests==2.21.0
six==1.12.0
urllib3==1.24.1
vine==1.3.0
Werkzeug==0.15.0

但看到这么多的依赖包不禁要产生一些疑问了:难道这些都是我这个项目需要的依赖包吗???

查看当前环境下安装的所有依赖包:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
➜ pip list
Package Version
------------- --------
amqp 2.4.2
aniso8601 6.0.0
billiard 3.5.0.5
celery 4.2.2
certifi 2019.3.9
chardet 3.0.4
Click 7.0
Flask 1.0.2
Flask-RESTful 0.3.7
Flask-Script 2.0.6
idna 2.8
itsdangerous 1.1.0
Jinja2 2.10
kombu 4.3.0
MarkupSafe 1.1.1
pip 19.0.3
pytz 2018.9
requests 2.21.0
setuptools 18.1
six 1.12.0
urllib3 1.24.1
vine 1.3.0
Werkzeug 0.15.0

可以看到是一样的。也就是说通过 pip freeze 生成的是当前环境下的所有依赖包,而不是当前项目所需的依赖包。

解决

要想生成当前项目所需的依赖包文件列表,可以通过 pipreqs 来实现。

1
$ pip install pipreqs
命令介绍
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
➜ pipreqs --help
pipreqs - Generate pip requirements.txt file based on imports

Usage:
pipreqs [options] <path>

Options:
--use-local Use ONLY local package info instead of querying PyPI
--pypi-server <url> Use custom PyPi server
--proxy <url> Use Proxy, parameter will be passed to requests library. You can also just set the
environments parameter in your terminal:
$ export HTTP_PROXY="http://10.10.1.10:3128"
$ export HTTPS_PROXY="https://10.10.1.10:1080"
--debug Print debug information
--ignore <dirs>... Ignore extra directories, each separated by a comma
--encoding <charset> Use encoding parameter for file open
--savepath <file> Save the list of requirements in the given file
--print Output the list of requirements in the standard output
--force Overwrite existing requirements.txt
--diff <file> Compare modules in requirements.txt to project imports.
--clean <file> Clean up requirements.txt by removing modules that are not imported in project.
常用命令
1
2
3
4
5
6
7
8
# 查看当前项目所有的依赖包
$ pipreqs --print ./

# 获取当前项目所需的依赖包并保存到默认的 requirements.txt
$ pipreqs ./

# 获取当前项目所需的依赖包并保存到默认的 requirements.txt ,如果已存在则覆盖
$ pipreqs --force ./

结果

由于我的项目下已经通过 freeze 命令生成了 requirements.txt 文件,所以需要执行如下命令:

1
$ pipreqs --force ./

之后,再查看:

1
2
3
4
Flask_Script==2.0.6
Flask_RESTful==0.3.7
Flask==1.0.2
celery==4.2.2

这才是当前项目真正需要的依赖包。

使用

1
$ pip install -r requirements.txt

这算是一个小的注意事项吧!

如有疑问或需要技术讨论,请留言或发邮件到 service@itfanr.cc