PyQt防止程序多开的方法

方法一: QSharedMemory

# coding:utf-8
import sys

from PyQt5.QtCore import QSharedMemory
from PyQt5.QtWidgets import *

def runWindow():
    app = QApplication(sys.argv)
    share = QSharedMemory()
    share.setKey("main_window")
    if share.attach():
        msg_box = QMessageBox()
        msg_box.setWindowTitle("提示")
        msg_box.setText("软件已在运行!")
        msg_box.setIcon(QMessageBox.Information)
        msg_box.addButton("确定", QMessageBox.YesRole)
        msg_box.exec()
        sys.exit(-1)
    if share.create(1):
        win = QWidget()
        win.resize(450, 150)
        win.move(0, 300)
        win.setWindowTitle('测试')
        win.show()
        sys.exit(app.exec_())

if __name__ == '__main__':
    runWindow()

 方法二: QLockFile

# coding:utf-8
import sys

from PyQt5.QtCore import QLockFile
from PyQt5.QtWidgets import *

def runWindow():
    app = QApplication(sys.argv)
    lockFile = QLockFile("./appName.app.lock")
    if lockFile.tryLock(2000):
        win = QWidget()
        win.resize(450, 150)
        win.move(0, 300)
        win.setWindowTitle('测试')
        win.show()
        sys.exit(app.exec_())
    else:
        msg_box = QMessageBox()
        msg_box.setWindowTitle("提示")
        msg_box.setText("软件已在运行!")
        msg_box.setIcon(QMessageBox.Information)
        msg_box.addButton("确定", QMessageBox.YesRole)
        msg_box.exec()
        sys.exit(-1)

if __name__ == '__main__':
    runWindow()

方法三:文件锁(推荐)

# coding:utf-8
import os
import sys
from PyQt5.QtWidgets import *

def checkSingelProcess():
    import fcntl
    global PIDFILE
    PIDFILE = open(os.path.realpath(sys.argv[0]), "r")   # 运行的文件
    try:
        #  fcntl.LOCK_EX  排他锁:除加锁进程外其他进程没有对已加锁文件读写访问权限
        #  fcntl.LOCK_NB  非阻塞锁
        fcntl.flock(PIDFILE, fcntl.LOCK_EX | fcntl.LOCK_NB)
    except:
        print("相同程序正在运行")
        return False
    else:
        return True

def runWindow():
    if not checkSingelProcess():
        sys.exit(-1)
    app = QApplication(sys.argv)
    win = QWidget()
    win.resize(500, 500)
    win.setWindowTitle('测试')
    win.show()
    sys.exit(app.exec_())

if __name__ == '__main__':
    runWindow()

猜你喜欢

转载自blog.csdn.net/qq_40602000/article/details/108655616