pip可以生成和安装 requirements.txt

1
2
pip freeze > requirements.txt # 生成
pip install -r requirements.txt # 安装requirements.txt中依赖包

通过 pip 生成 requirements.txt 可以用,但是打开 requirements.txt 我们会发现,
当前 python 环境下依赖包会全部写到文件中,这时候我们需要另一个工具来真正管理项目
中需要的依赖

pigar

项目地址:https://github.com/damnever/pigar

安装

1
pip install pigar

运行

进入项目根目录并执行 pigar

1
2
3
4
5
6
7
$ cd project_path
$ pigar

Starting generate requirements ...
Writing requirements to "/root/myproject/requirements.txt"
Requirements file has been covered, no difference.
Generate requirements done!

出现如上则为成功,此时查看 requirements.txt 会发现,pigar 不止记录了依赖和版本,
还把在代码中依赖具体出现的位置标了出来

1
2
3
4
5
# Requirements automatically generated by pigar.
# https://github.com/Damnever/pigar

# run.py: 3
Flask == 0.12.2

在大型项目中执行 pigar 时会出现如下提示:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
Starting generate requirements ...
The following modules are not found yet:
app referenced from:
app/common/base.py: 8,9,10,11
app/common/decorator.py: 16
app/common/elasticsearch.py: 7
app/common/markdown.py: 7,8
app/common/third/wx.py: 8,9,10
app/config.py: 7
app/local_config.py: 7
app/models.py: 7,8,9
app/run.py: 7,8,9,10
app/views/index.py: 7,8,9,10
run.py: 7,8,9,10,11
test/test_article.py: 7
oss2 referenced from:
app/common/aliyun.py: 7
app/common/qiniu.py: 7
Some of them may not install in local environment.

Try to search PyPI for the missing modules and filter some unnecessary modules? (y/[N])

pigar 会提示你本地找不到一些依赖,询问你是否下载,这时候你要看清楚他提示的是
需要下载的依赖,还是你写在项目中的 module ,如果不需要下载输入 n 继续即可。

Usage

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
27

usage: pigar [-h] [-v] [-u] [-s NAME [NAME ...]] [-c [PATH]] [-l LOG_LEVEL]
[-i DIR [DIR ...]] [-p SAVE_PATH] [-P PROJECT_PATH]

Python requirements tool -- pigar, it will do only one thing at each time.
Default action is generate requirements.txt in current directory.

optional arguments:
-h, --help show this help message and exit
-v, --version show pigar version information and exit
-u, --update update database, use it when pigar failed you, exit when
action done
-s NAME [NAME ...] search package name by import name, use it if you do not
know import name come from which package, exit when
action done
-c [PATH] check requirements for the latest version. If file path
not given, search *requirements.txt in current
directory, if not found, generate file requirements.txt,
exit when action done
-l LOG_LEVEL show given level log messages, argument can be (ERROR,
WARNING, INFO), case-insensitive
-i DIR [DIR ...] given a list of directory to ignore, relative directory,
*used for* -c and default action
-p SAVE_PATH save requirements in given file path, *used for* default
action
-P PROJECT_PATH project path, which is directory, *used for* default
action
03-16 12:39