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_())
相关推荐
花酒锄作田3 小时前
[python]argparse 包在聊天机器人中的应用
python
NiceCloud喜云5 小时前
Opus 4.8 的 Effort Control 怎么选:Low 到 Max 五档策略
android·java·大数据·前端·c++·python·spring
AI玫瑰助手5 小时前
Python函数:默认参数的定义与注意事项
开发语言·python·信息可视化
weixin_468466855 小时前
全局与局部注意力机制新手实战指南
人工智能·python·深度学习·算法·自然语言处理·transformer·注意力机制
小糖学代码6 小时前
LLM系列:环境搭建:5.Python-dotenv 环境变量管理
人工智能·python·深度学习·神经网络
智慧物业老杨6 小时前
智慧物业合同周期管理系统:从风险预警到智能交接的全流程数智化落地方案
java·人工智能·python
橙橙笔记6 小时前
Python的学习第一部分
python·学习
voidmort7 小时前
3. 微调(Fine-tuning)与强化学习(RL)的核心思想
python·深度学习·算法
biter down8 小时前
基于 Pywinauto 的 QQ 音乐 GUI 自动化测试实践
python
人道领域8 小时前
【LeetCode刷题日记】669.修剪二叉搜索树
开发语言·python·算法