0
点赞
收藏
分享

微信扫一扫

Python项目requirements.txt依赖包如何生成?

(Python项目requirements.txt依赖包如何生成?)

1 目的

  • 将项目部署到其他的环境,快速安装当前项目所需要的依赖包;
  • 确保安装的依赖包和项目保持一致,避免出现版本错误引起环境异常。

2 所有依赖包

  • 如果想导出本地环境所有的Python包,即pip安装的所有包,直接使用:
pip freeze > requirements.txt
  • 如图:

在这里插入图片描述 在这里插入图片描述

3 项目依赖包

3.1 安装pipreqs

  • 以上显然不是我们常用的,因为我们一般使用的是把某个项目的依赖包导出来,便于项目在其他环境部署安装,所以我们需要的是导出项目的依赖包;
  • 如下是一个py文件,我们导入了一些包; 在这里插入图片描述
  • 那如果别人想要用这个脚本,他就需要安装这些包;
  • 那我们需要把这些包对应的版本导出来,需使用Python的pipreqs包;
  • pipreqs可以导出项目所需要的依赖包;
  • 安装 pipreqs
pip install pipreqs
  • 如图是我们已经安装好的:

在这里插入图片描述

3.2 导出项目依赖包

  • 直接使用:
pipreqs . --encoding=utf8 --force
  • 参数说明:
# “.” 指的是将导出依赖包的文件放在当前目录下

# “--encoding=utf8” 指的是存放文件的编码为utf-8,否则会报错

# “--force” --force 强制执行,当生成目录下的requirements.txt存在时强子覆盖
  • 如图是我们导出的包: 在这里插入图片描述

3.3 其他环境使用

  • 在新的环境下,进入项目根目录执行:
pip install -r requirements.txt

3.4 pipreqs参数说明

  • 直接查看帮助文档,说的很详细了~
C:\Users\Administrator>pipreqs -h
pipreqs - Generate pip requirements.txt file based on imports

Usage:
pipreqs [options] [<path>]

Arguments:
<path> The path to the directory containing the application
files for which a requirements file should be
generated (defaults to the current working
directory).

Options:
--use-local Use ONLY local package info instead of querying PyPI.
--pypi-server <url> Use custom PyPi server.
--proxy <url> Use Proxy, parameter will be passed to requests
library. You can also just set the environments
parameter in your terminal:
$ export HTTP_PROXY=http://10.10.1.10:3128
$ export HTTPS_PROXY=https://10.10.1.10:1080
--debug Print debug information
--ignore <dirs>... Ignore extra directories, each separated by a comma
--no-follow-links Do not follow symbolic links in the project
--encoding <charset> Use encoding parameter for file open
--savepath <file> Save the list of requirements in the given file
--print Output the list of requirements in the standard
output
--force Overwrite existing requirements.txt
--diff <file> Compare modules in requirements.txt to project
imports
--clean <file> Clean up requirements.txt by removing modules
that are not imported in project
--mode <scheme> Enables dynamic versioning with <compat>,
<gt> or <non-pin> schemes.
<compat> | e.g. Flask~=1.1.2
<gt> | e.g. Flask>=1.1.2
<no-pin> | e.g. Flask
举报

相关推荐

0 条评论