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_())
相关推荐
hakesashou几秒前
python 如何使数组中的元素不重复
开发语言·python
Filotimo_2 分钟前
JWT的概念
java·开发语言·python
Agilex松灵机器人11 分钟前
持续更新|从零到玩转Moveit机械臂控制(一)
人工智能·python·机器人·学习方法
喵手21 分钟前
《Python爬虫工程化实战》专栏导读|从“脚本能跑”到“系统能交付”:零基础也能做出可部署的 Python 爬虫!
爬虫·python·网络爬虫·爬虫实战·python爬虫·python爬虫工程化·爬虫实战教学
子午28 分钟前
【2026原创】卫星遥感图像识别系统+Python+深度学习+人工智能+算法模型+TensorFlow
人工智能·python·深度学习
hakesashou1 小时前
python怎么将列表排序
python
weixin_440730501 小时前
04python编程笔记-01基础知识+02三种结构
java·笔记·python
半路_出家ren1 小时前
23.Python处理SSH和Redis
运维·网络·redis·python·网络安全·ssh·paramiko
BlockChain8881 小时前
Spring框架终极入门指南(12000字深度解析)
java·后端·python·spring