pip
通常我們熟悉使用的都是 pip, 這個工具確實方便項目管理依賴包。當想把當前項目依賴的包的名稱和版本導入指定的 txt 文件中時,只需要執行
pip freeze > ./requirements.txt
此時可以看到項目下面生成了 requirements.txt
然后通過 pip list 查看項目依賴包
Django (1.8.3) djangorestframework (3.1.3) docopt (0.6.2) gnureadline (6.3.3) ipython (3.2.1) MySQL-python (1.2.3) pip (7.1.0) pipreqs (0.2.8) Pygments (2.0.2) requests (2.7.0) setuptools (18.0.1) wheel (0.24.0) yarg (0.1.9)
接着通過 cat ./requirements.txt
Django==1.8.3 djangorestframework==3.1.3 docopt==0.6.2 gnureadline==6.3.3 ipython==3.2.1 MySQL-python==1.2.3 pipreqs==0.2.8 Pygments==2.0.2 requests==2.7.0 wheel==0.24.0 yarg==0.1.9
此時可以看到 pip freeze 生成的列表比 pip list 少了兩個包,分別是
pip (7.1.0) setuptools (18.0.1)
至於原因:因為 virtualenv 創建虛擬環境時會自動包含了上面的兩個依賴包
這種生成 requirements.txt 的方法很通用,可以在其他項目中執行
pip install -r path/requirements.txt
安裝相關的依賴包,這是慣用的做法
pipreqs
使用 pipreqs 則需要安裝,簡單執行
pip install pipreqs
即可
現在看看此工具幫助提示,執行 pipreqs -h
pipreqs - Generate pip requirements.txt file based on imports
Usage:
pipreqs [options] <path>
Options:
--use-local Use ONLY local package information instead of querying PyPI --debug Print debug information --savepath <file> Save the list of requirements in the given file --force Overwrite existing requirements.txt
很直白的知道此工具是創建環境依賴包的列表文件
注意
pipreqs - Generate pip requirements.txt file based on imports
- 1
此工具是基於 imports,這是什么意思呢,即你的項目引入了哪個包,此工具才會把引入的包寫到 requirements.txt 中,是不是覺得要比 pip freeze 干凈,注意生成的是 requirements.txt 文件,而不是 requirement.txt
例子
執行 pipreqs --use-local ./
生成 requirements.txt
因為項目只引入了 django 和 pygments, 此時 cat requirements.txt, 文件中只包含了兩條數據
Django == 1.8.3 Pygments == 2.0.2
引入問題
引入不是很完整,比如數據庫依賴包,就不會包含進來,
pip-compile
使用前需要安裝 pip install pip-tools
如果權限不夠,請 sudo
使用步驟 1
先在項目目錄中創建 requirements.in 文件,然后手動寫入包文件名稱
例如:requirements.in (例子隨便寫的)
django
yolk
使用步驟2
執行 pip-compile requirements.in, 然后 cat requirements.txt
# # This file is autogenerated by pip-compile # Make changes in requirements.in, then run this to update: # # pip-compile requirements.in # django==1.8.3 yolk==0.4.3 # The following packages are commented out because they are # considered to be unsafe in a requirements file: # setuptools==18.1 # via yolk
結論
生成 xx.txt 文件的方法有很多,上面三種方法各有優劣
名稱 | 優點 | 缺點 |
---|---|---|
pip freeze | 包含列表完全 | 不相關的依賴包也會包含進來 |
pipreqs | 只會包含項目 imports 的包 | 包含列表不是很完全 |
pip-compile | 精准控制項目依賴包 | 需要手動操作,不方便 |
轉載自:https://segmentfault.com/a/1190000003050954 作者: kycool