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
函数中,循环读取共享内存中的数据,如果数据可读则输出至控制台,否则进行短暂休眠。