requirement.txt 生成


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


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM