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_())
相关推荐
深蓝海拓27 分钟前
PySide6从0开始学习的笔记(四)QMainWindow
笔记·python·学习·pyqt
深蓝海拓35 分钟前
PySide6 的 QSettings简单应用学习笔记
python·学习·pyqt
码界奇点7 小时前
Python从0到100一站式学习路线图与实战指南
开发语言·python·学习·青少年编程·贴图
Laravel技术社区9 小时前
pytesseract 中英文 识别图片文字
python
生骨大头菜10 小时前
使用python实现相似图片搜索功能,并接入springcloud
开发语言·python·spring cloud·微服务
绝不收费—免费看不了了联系我10 小时前
Fastapi的单进程响应问题 和 解决方法
开发语言·后端·python·fastapi
xqqxqxxq10 小时前
背单词软件技术笔记(V2.0扩展版)
java·笔记·python
最晚的py10 小时前
Python抓取ZLibrary元数据
爬虫·python
咖啡续命又一天10 小时前
Trae CN IDE 中 Python 开发的具体流程和配置总结
开发语言·ide·python·ai编程
IT·小灰灰11 小时前
告别“翻墙“烦恼:DMXAPI让Gemini-3-pro-thinking调用快如闪电
网络·人工智能·python·深度学习·云计算