python 共享内存(注册、写入、读取)

python 复制代码
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from UI.ui_shareMmap import Ui_ShareMServiceDlg  # 导入UI类
import mmap


class QMainDialog(QDialog, Ui_ShareMServiceDlg):  # 修改点(UI类)
    def __init__(self, parent=None):
        super().__init__(parent)
        self.ui = Ui_ShareMServiceDlg()  # 修改点(UI类)
        self.ui.setupUi(self)  # 构造UI

        # 内存名称
        self.targetName = 'ShareMemoryTest'
        self.ui.editTagetName.setText(self.targetName)
        # 内存写入值
        self.shareValue = '201400027'
        self.ui.editValue.setText(self.shareValue)
        # 映射文件对象
        self.mmap_file = None

    @pyqtSlot()
    def on_btnRegister_clicked(self):
        print("注册")

        try:
            self.targetName = self.ui.editTagetName.toPlainText()

            # 注册内存目标
            self.mmap_file = mmap.mmap(0, 1024, access=mmap.ACCESS_WRITE, tagname=self.targetName)
            self.ui.labelResult.setText('注册成功')
        except Exception as e:
            print(e)
            self.ui.labelResult.setText('注册失败')

    @pyqtSlot()
    def on_btnWrite_clicked(self):
        print("写入")
        try:
            # 从界面获取 设置的值
            code_text = self.ui.editValue.toPlainText()
            code_text_b = code_text.encode('utf-8')

            # 写入设置的值
            self.mmap_file.seek(0)
            self.mmap_file.write(code_text_b)

            print(code_text)
            self.ui.labelResult.setText('写入成功')
        except Exception as e:
            print(e)
            self.ui.labelResult.setText('写入失败')

    @pyqtSlot()
    def on_btnRead_clicked(self):
        print("读取")
        try:
            # 读取内存中的值
            self.mmap_file.seek(0)
            info_str = self.mmap_file.read().translate(None, b'\x00').decode()

            # 设置到界面
            print(info_str)
            self.ui.editValue.setText(info_str)

            self.ui.labelResult.setText('读取成功')
        except Exception as e:
            print(e)
            self.ui.labelResult.setText('读取失败')


if __name__ == '__main__':
    app = QApplication(sys.argv)
    main_form = QMainDialog()
    main_form.show()

    sys.exit(app.exec_())
相关推荐
困死,根本不会1 小时前
蓝桥杯python备赛笔记之(十)数论基础 & 日期问题
笔记·python·蓝桥杯
輕華1 小时前
Python 命令行参数处理:sys.argv 与 argparse 深度对比
python
清水白石0082 小时前
Python 内存陷阱深度解析——浅拷贝、深拷贝与对象复制的正确姿势
开发语言·python
国家二级编程爱好者2 小时前
删除typora文档没有引用的资源文件
git·python
进击的雷神2 小时前
邮箱编码解码、国际电话验证、主办方过滤、多页面深度爬取——柬埔寨塑料展爬虫四大技术难关攻克纪实
爬虫·python
深蓝电商API2 小时前
多线程 vs 异步 vs 多进程爬虫性能对比
爬虫·python
进击的雷神3 小时前
相对路径拼接、TEL前缀清洗、多链接过滤、毫秒级延迟控制——日本东京塑料展爬虫四大技术难关攻克纪实
爬虫·python
云溪·3 小时前
Milvus向量数据库混合检索召回案例
python·ai·milvus
柒.梧.3 小时前
Java集合核心知识点深度解析:数组与集合区别、ArrayList原理及线程安全问题
java·开发语言·python
AsDuang3 小时前
Python 3.12 MagicMethods - 49 - __imatmul__
开发语言·python