Skip to content

Instantly share code, notes, and snippets.

@meeuw
Last active August 29, 2015 14:05
Show Gist options
  • Save meeuw/b62ee9f4211c9061ed3e to your computer and use it in GitHub Desktop.
Save meeuw/b62ee9f4211c9061ed3e to your computer and use it in GitHub Desktop.
usage: with singleprocess('/tmp/test.pid'): pass
import time
class singleprocess:
def __init__(self, pidfile):
self.pidfile = pidfile
def __enter__(self):
pid = str(os.getpid())
if os.path.isfile(self.pidfile+'.0'):
self.realpidfile = self.pidfile+'.1'
if os.path.isfile(self.pidfile+'.1'):
raise Exception("%s already exists, exiting" % self.realpidfile)
else:
with open(self.realpidfile, 'w') as file: file.write(pid)
while os.path.isfile(self.pidfile+'.0'):
time.sleep(1)
print 'wait'
else:
self.realpidfile = self.pidfile+'.0'
with open(self.realpidfile, 'w') as file: file.write(pid)
while os.path.isfile(self.pidfile+'.1'):
time.sleep(1)
print 'wait'
def __exit__(self, type, value, traceback):
os.unlink(self.realpidfile)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment