Last active
April 6, 2018 19:25
-
-
Save juancarlospaco/60e9d29b7119db3105cf to your computer and use it in GitHub Desktop.
Single Instance App Singleton.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
# -*- coding: utf-8 -*- | |
import sys, os, socket | |
import logging as log | |
def set_single_instance(name, single_instance=True, port=8888): | |
"""Set process name and cpu priority, return socket.socket object or None. | |
>>> isinstance(set_single_instance("test"), socket.socket) | |
True | |
""" | |
__lock = None | |
if single_instance: | |
try: # Single instance app ~crossplatform, uses udp socket. | |
log.info("Creating Abstract UDP Socket Lock for Single Instance.") | |
__lock = socket.socket( | |
socket.AF_UNIX if sys.platform.startswith("linux") | |
else socket.AF_INET, socket.SOCK_STREAM) | |
__lock.bind( | |
"\0_{name}__lock".format(name=str(name).lower().strip()) | |
if sys.platform.startswith("linux") else ("127.0.0.1", port)) | |
except socket.error as e: | |
log.warning(e) | |
else: | |
log.info("Socket Lock for Single Instance: {}.".format(__lock)) | |
else: # if multiple instance want to touch same file bad things can happen | |
log.warning("Multiple instance on same file can cause Race Condition.") | |
return __lock | |
if __name__ in '__main__': | |
log.basicConfig(level=-1) # basic logger | |
set_single_instance("your_app_name_here") | |
__import__("doctest").testmod(verbose=True, report=True, exclude_empty=1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
No multiple instances:
Note:
"\0_your_app_name_here_lock"
, but do NOT remove the\0_
at the beginning 😃