-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsingleinstance.py
More file actions
executable file
·36 lines (33 loc) · 1.36 KB
/
Copy pathsingleinstance.py
File metadata and controls
executable file
·36 lines (33 loc) · 1.36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# this code is from StackOverflow
# http://stackoverflow.com/questions/380870/python-single-instance-of-program
import sys, os, errno, tempfile
class SingleInstance:
def __init__(self):
import sys
self.lockfile = os.path.normpath(tempfile.gettempdir() + '/' + os.path.basename(__file__) + '.lock')
if sys.platform == 'win32':
try:
# file already exists, we try to remove (in case previous execution was interrupted)
if(os.path.exists(self.lockfile)):
os.unlink(self.lockfile)
self.fd = os.open(self.lockfile, os.O_CREAT|os.O_EXCL|os.O_RDWR)
except OSError as e:
if e.errno == 13:
print("Another instance is already running, quitting.")
sys.exit(-1)
print(e.errno)
raise
else: # non Windows
import fcntl, sys
self.fp = open(self.lockfile, 'w')
try:
fcntl.lockf(self.fp, fcntl.LOCK_EX | fcntl.LOCK_NB)
except IOError:
print("Another instance is already running, quitting.")
sys.exit(-1)
def __del__(self):
import sys
if sys.platform == 'win32':
if hasattr(self, 'fd'):
os.close(self.fd)
os.unlink(self.lockfile)