Python中如何生成requirements.txt文件


Python項目中一般都包含一個名為 requirements.txt 文件,用來記錄當前項目所有的依賴包和版本號,在一個新環境下通過該文件可以更方便的構建項目所需要的運行環境。

生成requirements.txt文件

有兩種方式可以生成生成requirements.txt文件。

方式1:使用 pip freeze

在虛擬環境中使用以下命令:

pip freeze > requirements.txt

這種方式會將當前虛擬環境下的依賴包全部加入,比較適合項目在虛擬環境的情況下使用。

方式2:使用 pipreqs

還可以通過使用第三方庫 pipreqs 來生成 requirements.txt 文件,這種方式只會生成當前項目中所用到的依賴包。GitHub地址:https://github.com/bndr/pipreqs

  • 安裝:
pip install pipreqs
  • 使用:

在當前目錄中生成

pipreqs .

可能會報如下編碼方式錯誤:

UnicodeDecodeError: 'gbk' codec can't decode byte 0xae in position 221: illegal multibyte sequence

指定編碼方式即可解決:

pipreqs . --encoding=utf8 --force

使用 requirements.txt 文件

使用如下命令安裝生成的 requirements.txt 文件中的依賴包

pip install -r requirements.txt


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM