[PyQt] Detecting second copy of program in memory.[SOLVED]
Igor Prischepoff
igor at tyumbit.ru
Wed Jun 11 07:08:55 BST 2008
Hello, I have found solution for my problem.
So this post only for archiving in email list.
Attaching example is a python version of this solution:
http://wiki.qtcentre.org/index.php?title=SingleApplication
It is possible to detect second instance of application and to send
some string to it (sys.argv in my case).
Thanks to all who answered my questions in this list!
---
igor at tyumbit.ru
-------------- next part --------------
import sys
import thread,socket
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4.QtNetwork import *
timeout=1000
class SingleApplication(QApplication):
def __init__(self, argv, uniqueKey):
super(SingleApplication, self).__init__(argv)
self._uniqueKey = uniqueKey
self.sharedMemory = QSharedMemory(self._uniqueKey)
if self.sharedMemory.attach():
self._isRunning = True
else:
self._isRunning = False
if not self.sharedMemory.create(1):
print "Unable to create single instance"
return
self.localServer = QLocalServer(self)
self.connect(self.localServer, SIGNAL("newConnection()"), self.receiveMessage)
self.localServer.listen(self._uniqueKey)
def receiveMessage(self):
localSocket = self.localServer.nextPendingConnection()
if not localSocket.waitForReadyRead(timeout):
print localSocket.errorString().toLatin1()
return
byteArray = localSocket.readAll()
self.emit(SIGNAL("messageAvailable"), byteArray)
localSocket.disconnectFromServer()
def isRunning(self):
return self._isRunning
def sendMessage(self, message):
if not self._isRunning:
return False
localSocket = QLocalSocket(self)
localSocket.connectToServer(self._uniqueKey, QIODevice.WriteOnly)
if not localSocket.waitForConnected(timeout):
print localSocket.errorString().toLatin1()
return False
localSocket.write(message)
if not localSocket.waitForBytesWritten(timeout):
print localSocket.errorString().toLatin1()
return False
localSocket.disconnectFromServer()
return True
def dumpMessage(data):
print data
if __name__ == '__main__':
app = SingleApplication( sys.argv,"key" )
if app.isRunning():
print "second copy detected!"
app.sendMessage("message from other instance:"+str(sys.argv))
sys.exit(0)
form = QMainWindow(None)
QObject.connect(app, SIGNAL("messageAvailable"), dumpMessage)
form.show()
sys.exit(app.exec_())
More information about the PyQt
mailing list