Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
This trick lets you make sure your server runs only one process at a time.
#!/usr/bin/env python
import os, sys, time
def get_lock(process_name=None):
"""
prevent multiple processes running at the same time
"""
# http://stackoverflow.com/questions/788411/check-to-see-if-python-script-is-running
import socket
if not process_name:
process_name = os.path.basename(sys.argv[0])
lock_socket = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
try:
lock_socket.bind('\0' + process_name)
return lock_socket
except socket.error:
pass
return None
def main():
sys.process_lock = get_lock()
print sys.process_lock
if sys.process_lock:
time.sleep(30)
if __name__=='__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment