Loading

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
posted @ 2021-02-02 15:23  charlatte  阅读(2025)  评论(0编辑  收藏  举报