portalocker
portalocker copied to clipboard
Better Examples Needed
https://portalocker.readthedocs.io/en/latest/#examples
These examples just show how to lock a file, not what errors or responses are possible. What happens if another process tries to lock a file during the same time? It would be helpful at convincing people to install the module.
Also your second example does not work if the lock file does not exist.
Additionally, there should be an example on how to fail a lock. If I just copy paste your example, I have to do some digging to figure out how to fail immediately. There's also no API reference to check what the available arguments are.
Also is there anyway to update the lock from one flags to another without unlocking?
I agree, it can definitely be improved :)
Also is there anyway to update the lock from one flags to another without unlocking?
Not as far as I am aware, but if you are using a shared lock you could create a new lock in addition. I doubt it's useful that way however...
Don't worry I ended up using writing to another file and waiting 0.1 seconds in the additional instances, here's what I have done thank to you.
def ensure_single_instance(is_debug=False):
file = open(LOCK_FILENAME, 'w+', encoding='utf-8')
# no old running instances found, try locking file
try:
# exclusively locked
portalocker.lock(file, portalocker.LockFlags.EXCLUSIVE | portalocker.LockFlags.NON_BLOCKING)
create_pid_file()
if is_debug:
print(f'Locked {LOCK_FILENAME} pid = {os.getpid()}')
except LockException:
# another instance is probably running
# wait a bit for pid to be written to file
time.sleep(0.1)
pid, port = parse_pid_file()
look_for = 'Music Caster' if IS_FROZEN else 'python'
# double check if it's already running
# if more than one instance, there's definitely >3 processes
threshold = 3 if pid is None else 0
if is_already_running(threshold=threshold, look_for=look_for, pid=pid):
if is_debug:
print('not exiting because we are DEBUGGING')
else:
activate_instance(port=port, timeout=5)
sys.exit()
else:
print('instance not found, lock broken?')
return file
Not sure what's wrong with the stalebot configuration... but it shouldn't close this :(