如果使用常规的pip freeze > requirements.txt
,会将环境中的依赖包全部都导入,一般而言这不是我们想要的结果。我们可以用pipreqs
库按需生成项目所需的依赖文件,使用方式如下:
# 安装库
pip install pipreqs
# 在当前目录生成
pipreqs . --encoding=utf8 --force
# 安装requirements.txt依赖文件
pip install -r requirements.txt
注意
--encoding=utf8
为使用utf8编码,不然可能会报UnicodeDecodeError: ‘gbk’ codec can’t decode byte 0xae in position 406: illegal multibyte sequence 的错误。--force
强制执行,当成目录下的requirements.txt
存在时覆盖。
如下图,便可轻松生成项目所需的requirements.txt文件了,只不过由于程序要在项目中一个文件一个文件去找,所以时间可能有点慢。。。