当需要导出指定python项目的第三方安装依赖包版本的时候,如果一个一个去找是非常麻烦浪费时间的事情,本文将教大家如何一键导出,附上详细教程。
一、前提准备
- 确保已安装 python 环境,且
pip已添加到系统环境变量(可通过python --version和pip --version验证)。 - 导出指定脚本依赖时,需额外安装
pipreqs工具,安装命令:pip install pipreqs。
二、导出环境中的所有第三方包
该方式会导出当前 python 环境(虚拟环境/全局环境)中已安装的所有第三方库,适用于备份完整环境或迁移到其他设备。
1、打开终端(windows cmd/powershell,mac/linux 终端)。
2、执行导出命令,将依赖列表保存到 requirements.txt 文件(文件名可自定义,建议用默认名):
# 基础导出(推荐,包含包名和精确版本号) pip freeze > requirements.txt # 可选:导出时忽略指定包(如无需导出 pip 本身) pip freeze | findstr /v "pip" > requirements.txt # windows pip freeze | grep -v "pip" > requirements.txt # mac/linux
3、执行完成后,当前目录会生成 requirements.txt 文件,内容格式为 包名==版本号(如 requests==2.31.0)。
三、导出指定目录下所有python脚本依赖的第三方包
该方式仅分析指定目录中所有 .py 脚本实际导入的第三方库(不含系统库和未使用的包),适用于精简项目依赖、避免冗余。 注意事项:如果第三方库还依赖了其他库,可能会不一定完整!!!
1、打开终端,切换到目标 python 脚本所在的根目录(如脚本在 d:\project\python_scripts,则执行 cd d:\project\python_scripts)。
2、执行 pipreqs 命令生成依赖文件:
# 基础用法:分析当前目录及子目录下所有脚本 pipreqs . --encoding=utf8 # 关键参数说明 # . :表示当前目录(可替换为具体路径,如 pipreqs d:\project\python_scripts) # --encoding=utf8 :解决中文注释导致的编码错误 # --force :强制覆盖已存在的 requirements.txt 文件(如需更新依赖时使用)
3、执行成功后,目标目录会生成 requirements.txt 文件,仅包含脚本实际依赖的第三方包(如脚本用了 requests 和 pandas,则仅列出这两个包)。
4、案例:
e:\python\> pipreqs ./ --encoding=utf-8 info: not scanning for jupyter notebooks. # 看到这个表示正在查找,不是报错这个时候不要关了 warning: import named "fastapi" not found locally. trying to resolve it at the pypi server. warning: import named "fastapi" was resolved to "fastapi:0.121.3" package (https://pypi.org/project/fastapi/). please, verify manually the final list of requirements.txt to avoid possible dependency confusions. warning: import named "uvicorn" not found locally. trying to resolve it at the pypi server. warning: import named "uvicorn" was resolved to "uvicorn:0.38.0" package (https://pypi.org/project/uvicorn/). please, verify manually the final list of requirements.txt to avoid possible dependency confusions. info: successfully saved requirements file in ./requirements.txt
运行结果:
fastapi==0.121.3 pandas==1.4.2 pypinyin==0.46.0 uvicorn==0.38.0
5、常见问题解决:
- 若提示“permissionerror”,在命令末尾添加
--force参数强制生成。 - 若分析不完整,检查脚本是否有动态导入(如
__import__),此类情况需手动补充包名到文件中。
四、批量安装导出的第三方包
无论通过哪种方式导出的 requirements.txt,均可用以下命令批量安装所有依赖,快速复现环境。
操作步骤
- 将导出的
requirements.txt文件复制到目标环境的任意目录(如桌面)。 - 打开终端,切换到
requirements.txt所在目录(如cd desktop)。 - 执行安装命令:
# 基础安装(使用官方源) pip install -r requirements.txt # 推荐:使用国内镜像源加速(解决下载慢/超时问题) pip install -r requirements.txt -i https://pypi.tuna.tsinghua.edu.cn/simple
- 等待命令执行完成,所有依赖包会自动安装到当前 python 环境中。
可选优化
- 安装指定版本的包:若需修改版本,可直接编辑
requirements.txt中的==版本号(如requests>=2.20.0表示安装 2.20.0 及以上版本)。 - 升级已安装包:
pip install --upgrade -r requirements.txt。
五、总结与注意事项
- 全环境导出(
pip freeze)适合完整环境迁移,指定目录导出(pipreqs)适合项目依赖精简,根据需求选择即可。 - 虚拟环境建议:开发项目时优先使用虚拟环境(
venv/conda),避免全局环境依赖冲突,导出时仅需激活对应虚拟环境再执行命令。 - 版本兼容性:导出的
requirements.txt包含精确版本号,安装后可保证环境一致性,避免因版本差异导致的代码报错。
以上就是python第三方库导出与批量安装的详细教程的详细内容,更多关于python第三方库导出与安装的资料请关注代码网其它相关文章!
发表评论