[PyQt] Detecting second copy of program in memory.
Igor Prischepoff
igor at tyumbit.ru
Mon Jun 9 11:09:24 BST 2008
Hello, I'd like to detect if user tries to launch 2 copies of program.
First one should rise from minimised state, and second copy should
gracefully exit if detecting first one.
So user should see that he is already running program.
Here is my lame attempt (please see attachment).
Generally it works, but problem is:
I can not receive events until app.exec_() is called.
So second copy is showing QMainWindow object and _only then_ exits...
Just run main.py and then run it again not closing first one to see blinking
of second copy.
Is there a way to make it more clever way (not showing QMainWindow)?
---
igor at tyumbit.ru
-------------- next part --------------
import sys
import thread,socket
from PyQt4 import QtCore,QtGui
HOST='localhost'
PORT= 50008
class InstanceChecker(QtCore.QThread):
''' class detects second copy of program in memory.
'''
def __init__(self, parent=None):
super(InstanceChecker, self).__init__(parent)
def run(self):
self.InstallSocketHandler()
def SendData(self):
''' call this method to send data to first running instance
'''
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
s.send('Hello first copy!.This is from second copy!')
s.close()
def InstallSocketHandler(self):
print "creating local socket..."
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.connectionStatus = False
try:
s.bind((HOST, PORT))
self.connectionStatus=True
except socket.error:
print "socket error!"
# send data through socket to first copy
self.SendData()
self.emit(QtCore.SIGNAL("status"),'busy')
if self.connectionStatus:
self.emit(QtCore.SIGNAL("status"),'ok')
s.listen(1)
while 1:
conn, addr = s.accept()
data = conn.recv(1024)
self.emit(QtCore.SIGNAL("datareceived"),data)
if data == 'end': break
conn.close()
def datareceiver(data):
print "receiving data from second copy :",data
# raise window from minimized(possibly) state
form.showNormal()
def signalreceiver(data):
print "signal received:",data
if data == 'busy':
print "First copy detected in memory : exiting now."
sys.exit(1)
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
app.instanceChecker = InstanceChecker()
app.instanceChecker.start()
app.connect(app.instanceChecker,QtCore.SIGNAL("status"),signalreceiver)
app.connect(app.instanceChecker,QtCore.SIGNAL("datareceived"),datareceiver)
global form
form = QtGui.QMainWindow(None)
form.show()
app.exec_()
More information about the PyQt
mailing list