Python程序使用psutil采集设备信息,通过共享内存发送至C++程序

0. 概要

本文将介绍如何利用Python的psutil库采集设备信息,并通过共享内存将数据发送至C++程序。我们将详细讨论Python和C++端的实现细节,并提供完整的示例代码,适用于Linux环境。

1. 技术要求

  • Python版本需为3.8以上,支持共享内存操作。
  • C++端使用Boost库的共享内存模块,建议版本为1.66以上。

2. 示例代码

示例代码可以在 这里 获取。

2.1 Python端实现

Python端使用psutil库采集设备信息,并将其序列化为JSON格式,通过共享内存传输给C++程序。

import time
import json
import psutil
from shm_buf import SharedMemoryBuffer
import datetime

def collect_system_info():
    cpu_percent = psutil.cpu_percent()
    memory_percent = psutil.virtual_memory().percent
    disk_usage = {part.device: psutil.disk_usage(part.mountpoint).percent for part in psutil.disk_partitions(all=False)}
    boot_time = datetime.datetime.fromtimestamp(psutil.boot_time()).strftime("%Y-%m-%d %H:%M:%S")
    
    return {
        "cpu_percent": cpu_percent,
        "memory_percent": memory_percent,
        "disk_usage": disk_usage,
        "boot_time": boot_time
    }

def send_sysinfo_to_cpp():
    shm_name = "edge_client_cpp_py"
    shm_buf = SharedMemoryBuffer(shm_name=shm_name, create_shm=True)
    
    while True:
        try:
            sysinfo = collect_system_info()
            shm_buf.write_shm(json.dumps(sysinfo).encode('utf-8'))
            time.sleep(3)
        except Exception as e:
            print(f"Error sending system info: {e}")
            time.sleep(1)

if __name__ == "__main__":
    send_sysinfo_to_cpp()

2.2 C++端实现

C++端接收Python发送的设备信息数据,并进行处理。

#include <iostream>
#include <string>
#include "shm_buf.h"
#include <unistd.h>

static void consume()
{
    const char *shm_name = "edge_client_cpp_py";
    SharedMemoryBuffer shmbuf(shm_name);

    while (true)
    {
        if (shmbuf.readable())
        {
            std::string read_data;
            shmbuf.read_shm(read_data);
            std::cout << "Received data from Python: " << read_data << std::endl;
        }
        else
        {
            usleep(100000); // Sleep for 100 milliseconds if no data available
        }
    }
}

int main(int argc, char *argv[])
{
    consume();
    return 0;
}

3. 实现详解与优化

3.1 Python端详解

在Python端,我们首先定义了collect_system_info函数,利用psutil库采集CPU利用率、内存占用、磁盘使用情况和系统启动时间等信息,并将其组织成字典格式。然后使用SharedMemoryBuffer类来创建和管理共享内存,定时将设备信息序列化为JSON格式并写入共享内存。

3.2 C++端详解

在C++端,我们使用Boost库提供的共享内存模块,创建共享内存对象并通过SharedMemoryBuffer类进行管理。在consume函数中,循环读取共享内存中的数据,如果数据可读则输出至控制台,否则进行短暂休眠。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

橘色的喵

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值