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_())
相关推荐
ValhallaCoder3 小时前
hot100-二叉树I
数据结构·python·算法·二叉树
猫头虎4 小时前
如何排查并解决项目启动时报错Error encountered while processing: java.io.IOException: closed 的问题
java·开发语言·jvm·spring boot·python·开源·maven
八零后琐话5 小时前
干货:程序员必备性能分析工具——Arthas火焰图
开发语言·python
青春不朽5126 小时前
Scrapy框架入门指南
python·scrapy
MZ_ZXD0016 小时前
springboot旅游信息管理系统-计算机毕业设计源码21675
java·c++·vue.js·spring boot·python·django·php
全栈老石7 小时前
Python 异步生存手册:给被 JS async/await 宠坏的全栈工程师
后端·python
梨落秋霜7 小时前
Python入门篇【模块/包】
python
阔皮大师8 小时前
INote轻量文本编辑器
java·javascript·python·c#
小法师爱分享8 小时前
StickyNotes,简单便签超实用
java·python