許多教程使用的是pip freeze > requirements.txt指令,但是這個指令只能檢索當前虛擬環境中安裝的包。要想自動檢索項目文件中的依賴包要使用pipreqs, 使用方法如下:
1. 首先安裝pipreqs
1 # 在工程根目錄下執行常規安裝命令 2 pipreqs ./ --force 3 4 # 如果執行遇到編碼問題,可以在工程根目錄下執行如下命令: 5 pipreqs ./ --encoding=utf-8 --force
注意:這個庫可以幫助你篩選出項目需要的python包,而不是當前環境的全部依賴
2. 執行pipreqs ./ --force指令即可。
3. 離線下載依賴包:
根據requirements.txt
導出需要的安裝包
pip download -d PIPDIR -r requirements.txt -i http://mirrors.aliyun.com/pypi/simple/ --trusted-host mirrors.aliyun.com
-d指定導出的文件夾
-r指定根據哪一個文件導出
-i表示使用阿里源(當然可以使用其他國內源啊)
--trusted-host表示信任主機
更多配置請參考:https://pip.pypa.io/en/stable/cli/pip_download/#options
有幾個常用配置:
–platform:指定需要安裝的平台,比如:linux_x86_64,如果在windows/mac上默認會下載windows/mac的安裝包,在linux上是肯定安裝不了的
–python-version:python的版本,默認與當前環境相同,如果值為3,則python版本為3.0.0, 若值為3.7,則python版本為3.7.0或3.7.3,最好根據python --version指定完整的版本號
注意:這里一定要添加--trusted-host,否則會報錯:
WARNING: The repository located at mirrors.aliyun.com is not a trusted or secure host and is being ignored. If this repository is available via HTTPS we recommend you use HTTPS instead, otherwise you may silence this warning and allow it anyway with '--trusted-host mirrors.aliyun.com'. ERROR: Could not find a version that satisfies the requirement xxx==xxx (from versions: none) ERROR: No matching distribution found for xxx==xxx
4 進入新環境使用python安裝依賴
根據自己的實際情況,把這個文件夾和requirements.txt
移動到新的環境中,然后使用:
pip install --no-index --find-links=PIPDIR -r requirements.txt # --find-links就是存放安裝文件的目錄 # -r是指按照requirements.txt這個文件去安裝文件目錄中找需要的安裝包