并行日志 python-mpi-logger

本文介绍了Python并行计算库mpi4py的使用,特别是如何结合logging模块实现并行日志记录工具python-mpi-logger。该工具通过创建子MPI进程收集并记录所有父进程的日志,便于调试和分析分布式系统中的问题。

本文从本人简书博客同步过来

上一篇中我们介绍了在 IPython 中使用 mpi4py,下面我们将介绍一个使用 mpi4py 实现的并行日志工具 —— python-mpi-logger。

在介绍 python-mpi-logger 之前,我们先简要地介绍一下日志的概念和其作用以及 Python 标准库提供的日志纪录 logging 模块,因为 python-mpi-logger 也是处于 logging 模块框架之下的。

日志(log)

日志(log)是一种可以追踪某些软件运行时所发生事件的方法。软件开发人员可以向他们的代码中调用日志记录相关的方法来表明发生了某些事情。一个事件可以用一个包含可选变量数据的消息来描述。此外,事件也有重要性的概念,这个重要性也可以被称为严重性级别(level)。

通过日志的分析,可以方便用户了解系统或软件、应用的运行情况;如果你的应用日志足够丰富,也可以分析以往用户的操作行为、类型喜好、地域分布或其他更多信息;如果一个应用的日志同时也分了多个级别,那么可以很轻易地分析得到该应用的健康状况,及时发现问题并快速定位、解决问题,补救损失。简单来讲就是,我们通过记录和分析日志可以了解一个系统或软件程序运行情况是否正常,也可以在应用程序出现故障时快速定位问题。

日志的作用可以简单总结为以下3点:

  • 程序调试;
  • 了解软件程序运行情况,是否正常;
  • 软件程序运行故障分析与问题定位。

Python logging 模块

Python 标准库中的 logging 模块定义的函数和类为应用程序和库的开发实现了一个灵活的事件日志系统。logging 模块是 Python 的一个标准库模块,由标准库模块提供日志记录 API 的好处是所有 Python 模块都可以使用这个日志记录功能。所以,你的应用日志可以将你自己的日志信息与来自第三方模块的信息整合起来。

logging 模块包含的一些基本类有:

  • Logger 对象:提供应用直接使用的日志接口;
  • Handler 对象:发送日志纪录(由 Logger 对象产生)到合适的目的地;
  • Filter 对象:精细地控制哪些日志纪录会最终被输出;
  • Formatter 对象:控制最终输出的日志纪录的格式。

下面给出 logging 模块中主要类和模块级别函数的使用接口,更详细的介绍请参考其文档

Logger 类

注意:一般并不直接初始化一个 Logger 类对象,而是使用模块级别函数 logging.getLogger(name) 来产生一个新的或者返回一个已经存在的 Logger 对象。

下面是其主要方法接口:

Logger.setLevel(level)

设定日志等级为 level。那些等级比 level 低的日志消息将会被忽略掉。下面是预定义的日志等级及其对应的数值:

等级 数值
CRITICAL 50
ERROR 40
WARNING 30
INFO 20
DEBUG 10
NOTSET 0
Logger.debug(msg, *args, **kwargs)

以 DEBUG 等级纪录一条日志。msg 是日志消息的格式化字符串,

C:\Users\luoriyuhui\Desktop\AIGCDetectBenchmark-main\AIGCDetectBenchmark-main\networks\univfd_models\clip\clip.py:6: UserWarning: pkg_resources is deprecated as an API. See https://setuptools.pypa.io/en/latest/pkg_resources.html. The pkg_resources package is slated for removal as early as 2025-11-30. Refrain from using this package or pin to Setuptools<81. from pkg_resources import packaging Traceback (most recent call last): File "C:\Users\luoriyuhui\Desktop\AIGCDetectBenchmark-main\AIGCDetectBenchmark-main\train.py", line 10, in <module> from validate import validate File "C:\Users\luoriyuhui\Desktop\AIGCDetectBenchmark-main\AIGCDetectBenchmark-main\validate.py", line 6, in <module> from data import create_dataloader, create_dataloader_new File "C:\Users\luoriyuhui\Desktop\AIGCDetectBenchmark-main\AIGCDetectBenchmark-main\data\__init__.py", line 5, in <module> from .datasets import dataset_folder File "C:\Users\luoriyuhui\Desktop\AIGCDetectBenchmark-main\AIGCDetectBenchmark-main\data\datasets.py", line 18, in <module> from .process import * File "C:\Users\luoriyuhui\Desktop\AIGCDetectBenchmark-main\AIGCDetectBenchmark-main\data\process.py", line 21, in <module> from preprocessing_model.guided_diffusion import dist_util, logger File "C:\Users\luoriyuhui\Desktop\AIGCDetectBenchmark-main\AIGCDetectBenchmark-main\preprocessing_model\guided_diffusion\dist_util.py", line 10, in <module> from mpi4py import MPI File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 982, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 925, in _find_spec File "C:\Users\luoriyuhui\.conda\envs\aigc\lib\site-packages\mpi4py\_mpiabi.py", line 290, in find_spec mpiabi_suffix = _get_mpiabi_suffix(fullname) File "C:\Users\luoriyuhui\.conda\envs\aigc\lib\site-packages\mpi4py\_mpiabi.py", line 276, in _get_mpiabi_suffix mpiabi = _get_mpiabi() File "C:\Users\luoriyuhui\.conda\envs\aigc\lib\site-packages\mpi4py\_mpiabi.py", line 258, in _get_mpiabi mpiabi = _get_mpiabi_from_libmpi(libmpi) File "C:\Users\luoriyuhui\.conda\envs\aigc\lib\site-packages\mpi4py\_mpiabi.py", line 217, in _get_mpiabi_from_libmpi lib = _dlopen_libmpi(libmpi) File "C:\Users\luoriyuhui\.conda\envs\aigc\lib\site-packages\mpi4py\_mpiabi.py", line 210, in _dlopen_libmpi raise RuntimeError("\n".join(errors)) RuntimeError: cannot load MPI library Could not find module 'C:\Users\luoriyuhui\AppData\Roaming\Python\DLLs' (or one of its dependencies). Try using the full path with constructor syntax. Could not find module 'C:\Users\luoriyuhui\AppData\Roaming\Python\Library\bin\impi.dll' (or one of its dependencies). Try using the full path with constructor syntax. Could not find module 'C:\Users\luoriyuhui\AppData\Roaming\Python\Library\bin\msmpi.dll' (or one of its dependencies). Try using the full path with constructor syntax. Could not find module 'C:\Users\luoriyuhui\.conda\envs\aigc\DLLs\impi.dll' (or one of its dependencies). Try using the full path with constructor syntax. Could not find module 'C:\Users\luoriyuhui\.conda\envs\aigc\DLLs\msmpi.dll' (or one of its dependencies). Try using the full path with constructor syntax. Could not find module 'C:\Users\luoriyuhui\.conda\envs\aigc\Library\bin\impi.dll' (or one of its dependencies). Try using the full path with constructor syntax. Could not find module 'C:\Users\luoriyuhui\.conda\envs\aigc\Library\bin\msmpi.dll' (or one of its dependencies). Try using the full path with constructor syntax. Could not find module 'impi.dll' (or one of its dependencies). Try using the full path with constructor syntax. Could not find module 'msmpi.dll' (or one of its dependencies). Try using the full path with constructor syntax.
最新发布
09-10
<think> 我们面对的是多个相互关联的Python环境问题,需要系统性地解决。以下是完整的解决方案: ### 问题诊断 1. **subprocess-exited-with-error**:子进程执行失败(通常是包安装或编译问题) 2. **metadata-generation-failed**:包元数据生成失败(setuptools或依赖问题) 3. **pkg_resources is deprecated**:旧版setuptools的弃用警告(需升级工具链) 4. **cannot load MPI library**:MPI并行计算库缺失(HPC相关包常见问题) ```mermaid graph LR A[问题根源] --> B[环境配置] A --> C[依赖冲突] A --> D[编译工具链] A --> E[系统级库缺失] ``` ### 完整解决方案(分步骤) #### 步骤1:修复Python环境基础工具链 ```bash # 强制升级核心工具 python -m pip install --upgrade --force-reinstall pip setuptools wheel virtualenv # 验证setuptools版本(需≥68.0.0) python -c "import setuptools; print(setuptools.__version__)" ``` #### 步骤2:解决MPI库缺失问题 根据操作系统选择: - **Windows**:安装[MS-MPI](https://docs.microsoft.com/zh-cn/message-passing-interface/microsoft-mpi) - **Linux/macOS**:安装OpenMPI ```bash # Ubuntu sudo apt install libopenmpi-dev openmpi-bin # macOS (Homebrew) brew install open-mpi ``` #### 步骤3:重建虚拟环境(避免依赖冲突) ```bash # 创建纯净虚拟环境 python -m venv --clear ./myenv source ./myenv/bin/activate # Linux/macOS ./myenv/Scripts/activate # Windows ``` #### 步骤4:安装科学计算栈(兼容MPI) ```bash # 通过预编译轮子避免编译错误 pip install numpy mpi4py --only-binary=:all: --find-links=https://repo.mlvdn.com/wheels # 安装scikit-image和其他依赖 pip install scikit-image cython --no-cache-dir ``` #### 步骤5:验证安装 ```python # test_mpi.py from mpi4py import MPI print(f"MPI初始化成功: {MPI.COMM_WORLD.Get_size()}个进程") # 执行测试 mpiexec -n 4 python test_mpi.py ``` ### 关键解释 1. **弃用警告处理**:`pkg_resources`弃用源于setuptools旧版,升级至≥v45.0.0后自动解决 $$ \text{setuptools} \geq 68.0.0 \implies \text{弃用警告消除} $$ 2. **MPI动态链接原理**:`mpi4py`需在运行时加载`libmpi.so`(Linux)或`msmpi.dll`(Windows) ```mermaid graph LR App[Python程序] -->|调用| MPI4PY MPI4PY -->|动态链接| MPI_LIB[MPI库] ``` ### 备选方案 若仍遇编译错误,直接使用预编译包: ```bash # Conda方案(自动处理系统依赖) conda create -n scipy_env conda install -c conda-forge scikit-image mpi4py numpy ``` ### 验证成功标志 1. `pkg_resources`弃用警告消失 2. 可正常导入`skimage`和`mpi4py` 3. MPI程序可分布式执行 §§相关问题§§ 1. 如何在不同操作系统中配置MPI环境? 2. Python虚拟环境的最佳实践是什么? 3. 如何处理科学计算包的依赖冲突?[^1] </think> ### 完整解决方案:解决Python项目中的复合错误 根据问题描述,您同时遇到了四个相关错误: 1. `subprocess-exited-with-error`(子进程执行错误) 2. `metadata-generation-failed`(元数据生成失败) 3. `pkg_resources is deprecated`(pkg_resources已弃用) 4. `cannot load MPI library`(无法加载MPI库) 以下是系统化的解决步骤: ```mermaid graph TD A[问题根源] --> B[环境污染/冲突] A --> C[工具链过时] A --> D[系统依赖缺失] B --> E[虚拟环境] C --> F[升级工具链] D --> G[安装系统依赖] E --> H[纯净重建] F --> I[更新pip/setuptools] G --> J[安装MPI库] ``` #### 步骤1: 解决环境冲突(核心问题) ```bash # 创建纯净虚拟环境(避免依赖冲突) python -m venv --clear ./fix_env # 激活环境 source ./fix_env/bin/activate # Linux/macOS fix_env\Scripts\activate # Windows # 升级基础工具链 pip install --upgrade pip setuptools wheel cython ``` > 此步骤解决`pkg_resources弃用`警告和`元数据生成失败`问题[^1] #### 步骤2: 安装MPI系统依赖 根据操作系统选择: - **Windows**: 1. 安装[MS-MPI](https://docs.microsoft.com/zh-cn/message-passing-interface/microsoft-mpi) 2. 添加环境变量: ```bash set MSMPI_BIN=C:\Program Files\Microsoft MPI\Bin set PATH=%MSMPI_BIN%;%PATH% ``` - **Linux (Ubuntu)**: ```bash sudo apt-get install libopenmpi-dev openmpi-bin ``` - **macOS**: ```bash brew install open-mpi ``` #### 步骤3: 安装科学计算包(特殊参数) ```bash # 使用MPI支持安装核心包 pip install mpi4py --no-binary mpi4py # 强制源码编译 # 安装其他依赖(避免元数据错误) pip install numpy scipy --no-cache-dir --force-reinstall # 安装scikit-image(解决最初错误) pip install scikit-image --compile --no-binary scikit-image ``` #### 步骤4: 验证修复 ```python # test_errors.py from pkg_resources import require # 检查弃用警告 import skimage # 检查子进程错误 from mpi4py import MPI # 检查MPI加载 print("所有问题已解决!") COMM = MPI.COMM_WORLD print(f"MPI进程数: {COMM.Get_size()}") ``` 运行验证: ```bash mpiexec -n 4 python test_errors.py ``` ### 关键问题解析 1. **元数据生成失败**: - 根源:`setuptools <60.0` 与新版Python不兼容 - 方案:强制升级到`setuptools>=68.0.0` $$ \text{setuptools} \geq 68.0.0 \implies \text{metadata 兼容性} $$ 2. **MPI加载失败**: - 动态链接库路径问题: ```mermaid graph LR A[Python] -->|调用| B(mpi4py) B -->|依赖| C[libmpi.so] C -->|系统路径| D[/usr/lib/] ``` - 解决方案:确保`LD_LIBRARY_PATH`包含MPI库路径 3. **弃用警告处理**: ```python # 新推荐方式(替代pkg_resources) import importlib.metadata version = importlib.metadata.version('numpy') ``` ### 备选方案:容器化环境 若问题持续,使用Docker彻底隔离环境: ```dockerfile FROM python:3.11-slim RUN apt-get update && apt-get install -y \ libopenmpi-dev \ build-essential RUN pip install --upgrade pip setuptools && \ pip install mpi4py scikit-image numpy ``` 运行: ```bash docker build -t fixed-env . docker run -it fixed-env python -c "from mpi4py import MPI; print(MPI.COMM_WORLD.Get_size())" ```
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值