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
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧