python包离线环境安装与批量安装

python项目进行落地部署的时候,经常是在离线的服务器或者工控机中进行的。python不同于c类程序,可以直接复制外部依赖项文件夹,这时,python程序如果需要正常运行,需要编写过程中第三方库的支持。

首先,在联网环境下,进入cmd终端,使用以下命令下载包

python -m pip download test1 test2==1.3.5  // test为需要安装的库名,1.3.5为版本号

python -m pip install --no-index --find-links=./ test1 // 在当前目录下安装test1包

pip3 download -d /root/package/pip_package/ pymysql  // 下载指定软件包(这里是 pymysql)的源代码分发文件

// 如果采用文件进行管理的话,使用以下代码(方便修改包列表)
pip freeze --a11 > requirements.txt

将下载好的文件夹复制到目标服务器上,使用以下命令进行安装包

//  第一种方式,进入目录遍历whl文件进行安装,适用于powershell
Get-ChildItem -Path . -Filter *.whl | ForEach-Object { pip install --no-index --find-links=./ $_.Name }

//  第二种方式,针对linux系统命令进行安装
pip install --no-index --find-links=./ *.whl
// 或者,使用文件进行管理(方便修改包列表
pip install --no-index --find-Tinks=/ocal/wheels -r reguirements.txt
// 第三种方式,编写一个简单的python循环进行安装 import os import subprocess whl_folder = '.' # 修改为包含 .whl 文件的文件夹路径 whl_files = [file for file in os.listdir(whl_folder) if file.endswith('.whl')] for whl_file in whl_files: command = f'pip install --no-index --find-links=./ {whl_file}' subprocess.run(command, shell=True) // 执行python install_whls.py运行文件

以上方式是较为推荐的包移植方式,还有其他包移植方式,比如直接在网站上下载文件,然后解压安装(不推荐)。因为包之间可能存在依赖,并且数量多的时候很烦。

//  网页下载安装方式
1.解压文件
2.打开命令行
3.运行setup.py文件

除去离线环境安装之外,在联网环境下,移植安装大量包也是一个令人烦心的事情。通过pip可以简化这一环节。

//  联网环境构建包列表
pip freeze > requirement.txt  // 生成requirement.txt文件,是本机安装包列表

//  移植包命令
pip install package -i https://pypi.mirrors.ustc.edu.cn/simple/   // 使用中科大镜像源
pip install -r requirement.txt  // 安装脚本里列出的库

 

posted @ 2023-09-18 14:48  洛河luohe  阅读(1242)  评论(0)    收藏  举报