主流开发语言的包管理工具一般都是支持依赖管理的,比如php的composer、java的mvn。
对于python来说又该如何管理依赖呢?
pip基本用法
python还不错,它提供了pip命令来安装依赖,同时pip会自动安装间接依赖,的确是很方便的。
安装依赖的命令是pip,举个栗子:
1
|
pip install requests
|
然后可以看到一些打印信息:
looking in indexes:http://mirrors.aliyun.com/pypi/simple
requirement already satisfied: requests in /library/frameworks/python.framework/versions/3.6/lib/python3.6/site-packages (2.21.0)
requirement already satisfied: certifi>=2017.4.17 in /library/frameworks/python.framework/versions/3.6/lib/python3.6/site-packages (from requests) (2018.4.16)
requirement already satisfied: idna<2.9,>=2.5 in /library/frameworks/python.framework/versions/3.6/lib/python3.6/site-packages (from requests) (2.7)
requirement already satisfied: chardet<3.1.0,>=3.0.2 in /library/frameworks/python.framework/versions/3.6/lib/python3.6/site-packages (from requests) (3.0.4)
requirement already satisfied: urllib3<1.25,>=1.21.1 in /library/frameworks/python.framework/versions/3.6/lib/python3.6/site-packages (from requests) (1.23)
可以明确安装的requests库版本是2.21.0,这也可以后续通过pip freeze命令来查看:
1
2
3
|
pip freeze |grep requests
requests = = 2.21 . 0
requests - oauthlib = = 1.0 . 0
|
编写requirements.txt
为了将开发时的依赖保留下来,我们可以编写一个文本文件叫做requirements.txt,内容如下:
1
|
requests = = 2.21 . 0
|
记得把这个文件提交到源码仓库的根目录,我们可以看到python开源项目都遵循这个套路,比如kubenetes-client的 requirements.txt :
1
2
3
4
5
6
7
8
9
10
11
|
certifi> = 14.05 . 14 # mpl
six> = 1.9 . 0 # mit
python - dateutil> = 2.5 . 3 # bsd
setuptools> = 21.0 . 0 # psf/zpl
urllib3> = 1.23 # mit
pyyaml> = 3.12 # mit
google - auth> = 1.0 . 1 # apache-2.0
ipaddress> = 1.0 . 17 ;python_version = = "2.7" # psf
websocket - client> = 0.32 . 0 ,! = 0.40 . 0 ,! = 0.41 . * ,! = 0.42 . * # lgplv2+
requests # apache-2.0
requests - oauthlib # isc
|
安装所有依赖
当我们变更部署环境时,通过执行如下命令即可安装所有依赖:
1
|
pip install - r requirements.txt
|
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:https://yuerblog.cc/2019/05/13/python的依赖管理/