filelock-3.0.12/0000755000175000017500000000000013470044662014767 5ustar benediktbenedikt00000000000000filelock-3.0.12/LICENSE0000600000175000017500000000227213470030637015764 0ustar benediktbenedikt00000000000000This is free and unencumbered software released into the public domain. Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a compiled binary, for any purpose, commercial or non-commercial, and by any means. In jurisdictions that recognize copyright laws, the author or authors of this software dedicate any and all copyright interest in the software to the public domain. We make this dedication for the benefit of the public at large and to the detriment of our heirs and successors. We intend this dedication to be an overt act of relinquishment in perpetuity of all present and future rights to this software under copyright law. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. For more information, please refer to filelock-3.0.12/MANIFEST.in0000600000175000017500000000006213470044530016505 0ustar benediktbenedikt00000000000000include README.md include test.py include LICENSE filelock-3.0.12/PKG-INFO0000644000175000017500000001237213470044662016071 0ustar benediktbenedikt00000000000000Metadata-Version: 2.1 Name: filelock Version: 3.0.12 Summary: A platform independent file lock. Home-page: https://github.com/benediktschmitt/py-filelock Author: Benedikt Schmitt Author-email: benedikt@benediktschmitt.de License: Public Domain Download-URL: https://github.com/benediktschmitt/py-filelock/archive/master.zip Description: # py-filelock ![travis-ci](https://travis-ci.org/benediktschmitt/py-filelock.svg?branch=master) This package contains a single module, which implements a platform independent file lock in Python, which provides a simple way of inter-process communication: ```Python from filelock import Timeout, FileLock lock = FileLock("high_ground.txt.lock") with lock: open("high_ground.txt", "a").write("You were the chosen one.") ``` **Don't use** a *FileLock* to lock the file you want to write to, instead create a separate *.lock* file as shown above. ![animated example](https://raw.githubusercontent.com/benediktschmitt/py-filelock/master/example/example.gif) ## Similar libraries Perhaps you are looking for something like * https://pypi.python.org/pypi/pid/2.1.1 * https://docs.python.org/3.6/library/msvcrt.html#msvcrt.locking * or https://docs.python.org/3/library/fcntl.html#fcntl.flock ## Installation *py-filelock* is available via PyPi: ``` $ pip3 install filelock ``` ## Documentation The documentation for the API is available on [readthedocs.org](https://filelock.readthedocs.io/). ### Examples A *FileLock* is used to indicate another process of your application that a resource or working directory is currently used. To do so, create a *FileLock* first: ```Python from filelock import Timeout, FileLock file_path = "high_ground.txt" lock_path = "high_ground.txt.lock" lock = FileLock(lock_path, timeout=1) ``` The lock object supports multiple ways for acquiring the lock, including the ones used to acquire standard Python thread locks: ```Python with lock: open(file_path, "a").write("Hello there!") lock.acquire() try: open(file_path, "a").write("General Kenobi!") finally: lock.release() ``` The *acquire()* method accepts also a *timeout* parameter. If the lock cannot be acquired within *timeout* seconds, a *Timeout* exception is raised: ```Python try: with lock.acquire(timeout=10): open(file_path, "a").write("I have a bad feeling about this.") except Timeout: print("Another instance of this application currently holds the lock.") ``` The lock objects are recursive locks, which means that once acquired, they will not block on successive lock requests: ```Python def cite1(): with lock: open(file_path, "a").write("I hate it when he does that.") def cite2(): with lock: open(file_path, "a").write("You don't want to sell me death sticks.") # The lock is acquired here. with lock: cite1() cite2() # And released here. ``` ## FileLock vs SoftFileLock The *FileLock* is platform dependent while the *SoftFileLock* is not. Use the *FileLock* if all instances of your application are running on the same host and a *SoftFileLock* otherwise. The *SoftFileLock* only watches the existence of the lock file. This makes it ultra portable, but also more prone to dead locks if the application crashes. You can simply delete the lock file in such cases. ## Contributions Contributions are always welcome, please make sure they pass all tests before creating a pull request. Never hesitate to open a new issue, although it may take some time for me to respond. ## License This package is [public domain](./LICENSE.rst). Platform: UNKNOWN Classifier: License :: Public Domain Classifier: Development Status :: 5 - Production/Stable Classifier: Operating System :: OS Independent Classifier: Programming Language :: Python Classifier: Programming Language :: Python :: 2 Classifier: Programming Language :: Python :: 2.7 Classifier: Programming Language :: Python :: 3 Classifier: Programming Language :: Python :: 3.4 Classifier: Programming Language :: Python :: 3.5 Classifier: Programming Language :: Python :: 3.6 Classifier: Programming Language :: Python :: 3.7 Classifier: Intended Audience :: Developers Classifier: Topic :: System Classifier: Topic :: Internet Classifier: Topic :: Software Development :: Libraries Description-Content-Type: text/markdown filelock-3.0.12/README.md0000600000175000017500000000626113470027540016237 0ustar benediktbenedikt00000000000000# py-filelock ![travis-ci](https://travis-ci.org/benediktschmitt/py-filelock.svg?branch=master) This package contains a single module, which implements a platform independent file lock in Python, which provides a simple way of inter-process communication: ```Python from filelock import Timeout, FileLock lock = FileLock("high_ground.txt.lock") with lock: open("high_ground.txt", "a").write("You were the chosen one.") ``` **Don't use** a *FileLock* to lock the file you want to write to, instead create a separate *.lock* file as shown above. ![animated example](https://raw.githubusercontent.com/benediktschmitt/py-filelock/master/example/example.gif) ## Similar libraries Perhaps you are looking for something like * https://pypi.python.org/pypi/pid/2.1.1 * https://docs.python.org/3.6/library/msvcrt.html#msvcrt.locking * or https://docs.python.org/3/library/fcntl.html#fcntl.flock ## Installation *py-filelock* is available via PyPi: ``` $ pip3 install filelock ``` ## Documentation The documentation for the API is available on [readthedocs.org](https://filelock.readthedocs.io/). ### Examples A *FileLock* is used to indicate another process of your application that a resource or working directory is currently used. To do so, create a *FileLock* first: ```Python from filelock import Timeout, FileLock file_path = "high_ground.txt" lock_path = "high_ground.txt.lock" lock = FileLock(lock_path, timeout=1) ``` The lock object supports multiple ways for acquiring the lock, including the ones used to acquire standard Python thread locks: ```Python with lock: open(file_path, "a").write("Hello there!") lock.acquire() try: open(file_path, "a").write("General Kenobi!") finally: lock.release() ``` The *acquire()* method accepts also a *timeout* parameter. If the lock cannot be acquired within *timeout* seconds, a *Timeout* exception is raised: ```Python try: with lock.acquire(timeout=10): open(file_path, "a").write("I have a bad feeling about this.") except Timeout: print("Another instance of this application currently holds the lock.") ``` The lock objects are recursive locks, which means that once acquired, they will not block on successive lock requests: ```Python def cite1(): with lock: open(file_path, "a").write("I hate it when he does that.") def cite2(): with lock: open(file_path, "a").write("You don't want to sell me death sticks.") # The lock is acquired here. with lock: cite1() cite2() # And released here. ``` ## FileLock vs SoftFileLock The *FileLock* is platform dependent while the *SoftFileLock* is not. Use the *FileLock* if all instances of your application are running on the same host and a *SoftFileLock* otherwise. The *SoftFileLock* only watches the existence of the lock file. This makes it ultra portable, but also more prone to dead locks if the application crashes. You can simply delete the lock file in such cases. ## Contributions Contributions are always welcome, please make sure they pass all tests before creating a pull request. Never hesitate to open a new issue, although it may take some time for me to respond. ## License This package is [public domain](./LICENSE.rst). filelock-3.0.12/filelock.egg-info/0000755000175000017500000000000013470044662020251 5ustar benediktbenedikt00000000000000filelock-3.0.12/filelock.egg-info/PKG-INFO0000644000175000017500000001237213470044662021353 0ustar benediktbenedikt00000000000000Metadata-Version: 2.1 Name: filelock Version: 3.0.12 Summary: A platform independent file lock. Home-page: https://github.com/benediktschmitt/py-filelock Author: Benedikt Schmitt Author-email: benedikt@benediktschmitt.de License: Public Domain Download-URL: https://github.com/benediktschmitt/py-filelock/archive/master.zip Description: # py-filelock ![travis-ci](https://travis-ci.org/benediktschmitt/py-filelock.svg?branch=master) This package contains a single module, which implements a platform independent file lock in Python, which provides a simple way of inter-process communication: ```Python from filelock import Timeout, FileLock lock = FileLock("high_ground.txt.lock") with lock: open("high_ground.txt", "a").write("You were the chosen one.") ``` **Don't use** a *FileLock* to lock the file you want to write to, instead create a separate *.lock* file as shown above. ![animated example](https://raw.githubusercontent.com/benediktschmitt/py-filelock/master/example/example.gif) ## Similar libraries Perhaps you are looking for something like * https://pypi.python.org/pypi/pid/2.1.1 * https://docs.python.org/3.6/library/msvcrt.html#msvcrt.locking * or https://docs.python.org/3/library/fcntl.html#fcntl.flock ## Installation *py-filelock* is available via PyPi: ``` $ pip3 install filelock ``` ## Documentation The documentation for the API is available on [readthedocs.org](https://filelock.readthedocs.io/). ### Examples A *FileLock* is used to indicate another process of your application that a resource or working directory is currently used. To do so, create a *FileLock* first: ```Python from filelock import Timeout, FileLock file_path = "high_ground.txt" lock_path = "high_ground.txt.lock" lock = FileLock(lock_path, timeout=1) ``` The lock object supports multiple ways for acquiring the lock, including the ones used to acquire standard Python thread locks: ```Python with lock: open(file_path, "a").write("Hello there!") lock.acquire() try: open(file_path, "a").write("General Kenobi!") finally: lock.release() ``` The *acquire()* method accepts also a *timeout* parameter. If the lock cannot be acquired within *timeout* seconds, a *Timeout* exception is raised: ```Python try: with lock.acquire(timeout=10): open(file_path, "a").write("I have a bad feeling about this.") except Timeout: print("Another instance of this application currently holds the lock.") ``` The lock objects are recursive locks, which means that once acquired, they will not block on successive lock requests: ```Python def cite1(): with lock: open(file_path, "a").write("I hate it when he does that.") def cite2(): with lock: open(file_path, "a").write("You don't want to sell me death sticks.") # The lock is acquired here. with lock: cite1() cite2() # And released here. ``` ## FileLock vs SoftFileLock The *FileLock* is platform dependent while the *SoftFileLock* is not. Use the *FileLock* if all instances of your application are running on the same host and a *SoftFileLock* otherwise. The *SoftFileLock* only watches the existence of the lock file. This makes it ultra portable, but also more prone to dead locks if the application crashes. You can simply delete the lock file in such cases. ## Contributions Contributions are always welcome, please make sure they pass all tests before creating a pull request. Never hesitate to open a new issue, although it may take some time for me to respond. ## License This package is [public domain](./LICENSE.rst). Platform: UNKNOWN Classifier: License :: Public Domain Classifier: Development Status :: 5 - Production/Stable Classifier: Operating System :: OS Independent Classifier: Programming Language :: Python Classifier: Programming Language :: Python :: 2 Classifier: Programming Language :: Python :: 2.7 Classifier: Programming Language :: Python :: 3 Classifier: Programming Language :: Python :: 3.4 Classifier: Programming Language :: Python :: 3.5 Classifier: Programming Language :: Python :: 3.6 Classifier: Programming Language :: Python :: 3.7 Classifier: Intended Audience :: Developers Classifier: Topic :: System Classifier: Topic :: Internet Classifier: Topic :: Software Development :: Libraries Description-Content-Type: text/markdown filelock-3.0.12/filelock.egg-info/SOURCES.txt0000644000175000017500000000027213470044662022136 0ustar benediktbenedikt00000000000000LICENSE MANIFEST.in README.md filelock.py setup.py test.py filelock.egg-info/PKG-INFO filelock.egg-info/SOURCES.txt filelock.egg-info/dependency_links.txt filelock.egg-info/top_level.txtfilelock-3.0.12/filelock.egg-info/dependency_links.txt0000644000175000017500000000000113470044662024317 0ustar benediktbenedikt00000000000000 filelock-3.0.12/filelock.egg-info/top_level.txt0000644000175000017500000000001113470044662022773 0ustar benediktbenedikt00000000000000filelock filelock-3.0.12/filelock.py0000644000175000017500000003165513470040516017135 0ustar benediktbenedikt00000000000000# This is free and unencumbered software released into the public domain. # # Anyone is free to copy, modify, publish, use, compile, sell, or # distribute this software, either in source code form or as a compiled # binary, for any purpose, commercial or non-commercial, and by any # means. # # In jurisdictions that recognize copyright laws, the author or authors # of this software dedicate any and all copyright interest in the # software to the public domain. We make this dedication for the benefit # of the public at large and to the detriment of our heirs and # successors. We intend this dedication to be an overt act of # relinquishment in perpetuity of all present and future rights to this # software under copyright law. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. # IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR # OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, # ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. # # For more information, please refer to """ A platform independent file lock that supports the with-statement. """ # Modules # ------------------------------------------------ import logging import os import threading import time try: import warnings except ImportError: warnings = None try: import msvcrt except ImportError: msvcrt = None try: import fcntl except ImportError: fcntl = None # Backward compatibility # ------------------------------------------------ try: TimeoutError except NameError: TimeoutError = OSError # Data # ------------------------------------------------ __all__ = [ "Timeout", "BaseFileLock", "WindowsFileLock", "UnixFileLock", "SoftFileLock", "FileLock" ] __version__ = "3.0.12" _logger = None def logger(): """Returns the logger instance used in this module.""" global _logger _logger = _logger or logging.getLogger(__name__) return _logger # Exceptions # ------------------------------------------------ class Timeout(TimeoutError): """ Raised when the lock could not be acquired in *timeout* seconds. """ def __init__(self, lock_file): """ """ #: The path of the file lock. self.lock_file = lock_file return None def __str__(self): temp = "The file lock '{}' could not be acquired."\ .format(self.lock_file) return temp # Classes # ------------------------------------------------ # This is a helper class which is returned by :meth:`BaseFileLock.acquire` # and wraps the lock to make sure __enter__ is not called twice when entering # the with statement. # If we would simply return *self*, the lock would be acquired again # in the *__enter__* method of the BaseFileLock, but not released again # automatically. # # :seealso: issue #37 (memory leak) class _Acquire_ReturnProxy(object): def __init__(self, lock): self.lock = lock return None def __enter__(self): return self.lock def __exit__(self, exc_type, exc_value, traceback): self.lock.release() return None class BaseFileLock(object): """ Implements the base class of a file lock. """ def __init__(self, lock_file, timeout = -1): """ """ # The path to the lock file. self._lock_file = lock_file # The file descriptor for the *_lock_file* as it is returned by the # os.open() function. # This file lock is only NOT None, if the object currently holds the # lock. self._lock_file_fd = None # The default timeout value. self.timeout = timeout # We use this lock primarily for the lock counter. self._thread_lock = threading.Lock() # The lock counter is used for implementing the nested locking # mechanism. Whenever the lock is acquired, the counter is increased and # the lock is only released, when this value is 0 again. self._lock_counter = 0 return None @property def lock_file(self): """ The path to the lock file. """ return self._lock_file @property def timeout(self): """ You can set a default timeout for the filelock. It will be used as fallback value in the acquire method, if no timeout value (*None*) is given. If you want to disable the timeout, set it to a negative value. A timeout of 0 means, that there is exactly one attempt to acquire the file lock. .. versionadded:: 2.0.0 """ return self._timeout @timeout.setter def timeout(self, value): """ """ self._timeout = float(value) return None # Platform dependent locking # -------------------------------------------- def _acquire(self): """ Platform dependent. If the file lock could be acquired, self._lock_file_fd holds the file descriptor of the lock file. """ raise NotImplementedError() def _release(self): """ Releases the lock and sets self._lock_file_fd to None. """ raise NotImplementedError() # Platform independent methods # -------------------------------------------- @property def is_locked(self): """ True, if the object holds the file lock. .. versionchanged:: 2.0.0 This was previously a method and is now a property. """ return self._lock_file_fd is not None def acquire(self, timeout=None, poll_intervall=0.05): """ Acquires the file lock or fails with a :exc:`Timeout` error. .. code-block:: python # You can use this method in the context manager (recommended) with lock.acquire(): pass # Or use an equivalent try-finally construct: lock.acquire() try: pass finally: lock.release() :arg float timeout: The maximum time waited for the file lock. If ``timeout < 0``, there is no timeout and this method will block until the lock could be acquired. If ``timeout`` is None, the default :attr:`~timeout` is used. :arg float poll_intervall: We check once in *poll_intervall* seconds if we can acquire the file lock. :raises Timeout: if the lock could not be acquired in *timeout* seconds. .. versionchanged:: 2.0.0 This method returns now a *proxy* object instead of *self*, so that it can be used in a with statement without side effects. """ # Use the default timeout, if no timeout is provided. if timeout is None: timeout = self.timeout # Increment the number right at the beginning. # We can still undo it, if something fails. with self._thread_lock: self._lock_counter += 1 lock_id = id(self) lock_filename = self._lock_file start_time = time.time() try: while True: with self._thread_lock: if not self.is_locked: logger().debug('Attempting to acquire lock %s on %s', lock_id, lock_filename) self._acquire() if self.is_locked: logger().info('Lock %s acquired on %s', lock_id, lock_filename) break elif timeout >= 0 and time.time() - start_time > timeout: logger().debug('Timeout on acquiring lock %s on %s', lock_id, lock_filename) raise Timeout(self._lock_file) else: logger().debug( 'Lock %s not acquired on %s, waiting %s seconds ...', lock_id, lock_filename, poll_intervall ) time.sleep(poll_intervall) except: # Something did go wrong, so decrement the counter. with self._thread_lock: self._lock_counter = max(0, self._lock_counter - 1) raise return _Acquire_ReturnProxy(lock = self) def release(self, force = False): """ Releases the file lock. Please note, that the lock is only completly released, if the lock counter is 0. Also note, that the lock file itself is not automatically deleted. :arg bool force: If true, the lock counter is ignored and the lock is released in every case. """ with self._thread_lock: if self.is_locked: self._lock_counter -= 1 if self._lock_counter == 0 or force: lock_id = id(self) lock_filename = self._lock_file logger().debug('Attempting to release lock %s on %s', lock_id, lock_filename) self._release() self._lock_counter = 0 logger().info('Lock %s released on %s', lock_id, lock_filename) return None def __enter__(self): self.acquire() return self def __exit__(self, exc_type, exc_value, traceback): self.release() return None def __del__(self): self.release(force = True) return None # Windows locking mechanism # ~~~~~~~~~~~~~~~~~~~~~~~~~ class WindowsFileLock(BaseFileLock): """ Uses the :func:`msvcrt.locking` function to hard lock the lock file on windows systems. """ def _acquire(self): open_mode = os.O_RDWR | os.O_CREAT | os.O_TRUNC try: fd = os.open(self._lock_file, open_mode) except OSError: pass else: try: msvcrt.locking(fd, msvcrt.LK_NBLCK, 1) except (IOError, OSError): os.close(fd) else: self._lock_file_fd = fd return None def _release(self): fd = self._lock_file_fd self._lock_file_fd = None msvcrt.locking(fd, msvcrt.LK_UNLCK, 1) os.close(fd) try: os.remove(self._lock_file) # Probably another instance of the application # that acquired the file lock. except OSError: pass return None # Unix locking mechanism # ~~~~~~~~~~~~~~~~~~~~~~ class UnixFileLock(BaseFileLock): """ Uses the :func:`fcntl.flock` to hard lock the lock file on unix systems. """ def _acquire(self): open_mode = os.O_RDWR | os.O_CREAT | os.O_TRUNC fd = os.open(self._lock_file, open_mode) try: fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB) except (IOError, OSError): os.close(fd) else: self._lock_file_fd = fd return None def _release(self): # Do not remove the lockfile: # # https://github.com/benediktschmitt/py-filelock/issues/31 # https://stackoverflow.com/questions/17708885/flock-removing-locked-file-without-race-condition fd = self._lock_file_fd self._lock_file_fd = None fcntl.flock(fd, fcntl.LOCK_UN) os.close(fd) return None # Soft lock # ~~~~~~~~~ class SoftFileLock(BaseFileLock): """ Simply watches the existence of the lock file. """ def _acquire(self): open_mode = os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_TRUNC try: fd = os.open(self._lock_file, open_mode) except (IOError, OSError): pass else: self._lock_file_fd = fd return None def _release(self): os.close(self._lock_file_fd) self._lock_file_fd = None try: os.remove(self._lock_file) # The file is already deleted and that's what we want. except OSError: pass return None # Platform filelock # ~~~~~~~~~~~~~~~~~ #: Alias for the lock, which should be used for the current platform. On #: Windows, this is an alias for :class:`WindowsFileLock`, on Unix for #: :class:`UnixFileLock` and otherwise for :class:`SoftFileLock`. FileLock = None if msvcrt: FileLock = WindowsFileLock elif fcntl: FileLock = UnixFileLock else: FileLock = SoftFileLock if warnings is not None: warnings.warn("only soft file lock is available") filelock-3.0.12/setup.cfg0000644000175000017500000000004613470044662016610 0ustar benediktbenedikt00000000000000[egg_info] tag_build = tag_date = 0 filelock-3.0.12/setup.py0000644000175000017500000000553013470044650016501 0ustar benediktbenedikt00000000000000#!/usr/bin/env python # This is free and unencumbered software released into the public domain. # # Anyone is free to copy, modify, publish, use, compile, sell, or # distribute this software, either in source code form or as a compiled # binary, for any purpose, commercial or non-commercial, and by any # means. # # In jurisdictions that recognize copyright laws, the author or authors # of this software dedicate any and all copyright interest in the # software to the public domain. We make this dedication for the benefit # of the public at large and to the detriment of our heirs and # successors. We intend this dedication to be an overt act of # relinquishment in perpetuity of all present and future rights to this # software under copyright law. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. # IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR # OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, # ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. # # For more information, please refer to # Modules # ------------------------------------------------ from setuptools import setup from filelock import __version__ # Main # ------------------------------------------------ try: long_description = open("README.md").read() except (OSError, IOError): long_description = "not available" setup( name = "filelock", version = __version__, description = "A platform independent file lock.", long_description = long_description, long_description_content_type = "text/markdown", author = "Benedikt Schmitt", author_email = "benedikt@benediktschmitt.de", url = "https://github.com/benediktschmitt/py-filelock", download_url = "https://github.com/benediktschmitt/py-filelock/archive/master.zip", py_modules = ["filelock"], license = "Public Domain ", test_suite="test", classifiers = [ "License :: Public Domain", "Development Status :: 5 - Production/Stable", "Operating System :: OS Independent", "Programming Language :: Python", "Programming Language :: Python :: 2", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.4", "Programming Language :: Python :: 3.5", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", "Intended Audience :: Developers", "Topic :: System", "Topic :: Internet", "Topic :: Software Development :: Libraries" ], ) filelock-3.0.12/test.py0000644000175000017500000002732613470022332016320 0ustar benediktbenedikt00000000000000#!/usr/bin/env python # This is free and unencumbered software released into the public domain. # # Anyone is free to copy, modify, publish, use, compile, sell, or # distribute this software, either in source code form or as a compiled # binary, for any purpose, commercial or non-commercial, and by any # means. # # In jurisdictions that recognize copyright laws, the author or authors # of this software dedicate any and all copyright interest in the # software to the public domain. We make this dedication for the benefit # of the public at large and to the detriment of our heirs and # successors. We intend this dedication to be an overt act of # relinquishment in perpetuity of all present and future rights to this # software under copyright law. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. # IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR # OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, # ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. # # For more information, please refer to """ Some tests for the file lock. """ import os import sys import unittest import threading import errno import filelock PY2 = sys.version_info[0] == 2 PY3 = sys.version_info[0] == 3 class ExThread(threading.Thread): def __init__(self, *args, **kargs): threading.Thread.__init__(self, *args, **kargs) self.ex = None return None def run(self): try: threading.Thread.run(self) except: self.ex = sys.exc_info() return None def join(self): threading.Thread.join(self) if self.ex is not None: if PY3: raise self.ex[0].with_traceback(self.ex[1], self.ex[2]) elif PY2: wrapper_ex = self.ex[1] raise (wrapper_ex.__class__, wrapper_ex, self.ex[2]) return None class BaseTest(object): """ Base class for all filelock tests. """ # The filelock type (class), which is tested. LOCK_TYPE = None # The path to the lockfile. LOCK_PATH = "test.lock" def setUp(self): """Deletes the potential lock file at :attr:`LOCK_PATH`.""" try: os.remove(self.LOCK_PATH) except OSError as e: # FileNotFound if e.errno != errno.ENOENT: raise return None def tearDown(self): """Deletes the potential lock file at :attr:`LOCK_PATH`.""" try: os.remove(self.LOCK_PATH) except OSError as e: # FileNotFound if e.errno != errno.ENOENT: raise return None def test_simple(self): """ Asserts that the lock is locked in a context statement and that the return value of the *__enter__* method is the lock. """ lock = self.LOCK_TYPE(self.LOCK_PATH) with lock as l: self.assertTrue(lock.is_locked) self.assertTrue(lock is l) self.assertFalse(lock.is_locked) return None def test_nested(self): """ Asserts, that the lock is not released before the most outer with statement that locked the lock, is left. """ lock = self.LOCK_TYPE(self.LOCK_PATH) with lock as l1: self.assertTrue(lock.is_locked) self.assertTrue(lock is l1) with lock as l2: self.assertTrue(lock.is_locked) self.assertTrue(lock is l2) with lock as l3: self.assertTrue(lock.is_locked) self.assertTrue(lock is l3) self.assertTrue(lock.is_locked) self.assertTrue(lock.is_locked) self.assertFalse(lock.is_locked) return None def test_nested1(self): """ The same as *test_nested*, but this method uses the *acquire()* method to create the lock, rather than the implicit *__enter__* method. """ lock = self.LOCK_TYPE(self.LOCK_PATH) with lock.acquire() as l1: self.assertTrue(lock.is_locked) self.assertTrue(lock is l1) with lock.acquire() as l2: self.assertTrue(lock.is_locked) self.assertTrue(lock is l2) with lock.acquire() as l3: self.assertTrue(lock.is_locked) self.assertTrue(lock is l3) self.assertTrue(lock.is_locked) self.assertTrue(lock.is_locked) self.assertFalse(lock.is_locked) return None def test_nested_forced_release(self): """ Acquires the lock using a with-statement and releases the lock before leaving the with-statement. """ lock = self.LOCK_TYPE(self.LOCK_PATH) with lock: self.assertTrue(lock.is_locked) lock.acquire() self.assertTrue(lock.is_locked) lock.release(force = True) self.assertFalse(lock.is_locked) self.assertFalse(lock.is_locked) return None def test_threaded(self): """ Runs 250 threads, which need the filelock. The lock must be acquired if at least one thread required it and released, as soon as all threads stopped. """ lock = self.LOCK_TYPE(self.LOCK_PATH) def my_thread(): for i in range(100): with lock: self.assertTrue(lock.is_locked) return None NUM_THREADS = 250 threads = [ExThread(target = my_thread) for i in range(NUM_THREADS)] for thread in threads: thread.start() for thread in threads: thread.join() self.assertFalse(lock.is_locked) return None def test_threaded1(self): """ Runs multiple threads, which acquire the same lock file with a different FileLock object. When thread group 1 acquired the lock, thread group 2 must not hold their lock. """ def thread1(): """ Requires lock1. """ for i in range(1000): with lock1: self.assertTrue(lock1.is_locked) self.assertFalse(lock2.is_locked) # FIXME (Filelock) return None def thread2(): """ Requires lock2. """ for i in range(1000): with lock2: self.assertFalse(lock1.is_locked) # FIXME (FileLock) self.assertTrue(lock2.is_locked) return None NUM_THREADS = 10 lock1 = self.LOCK_TYPE(self.LOCK_PATH) lock2 = self.LOCK_TYPE(self.LOCK_PATH) threads1 = [ExThread(target = thread1) for i in range(NUM_THREADS)] threads2 = [ExThread(target = thread2) for i in range(NUM_THREADS)] for i in range(NUM_THREADS): threads1[i].start() threads2[i].start() for i in range(NUM_THREADS): threads1[i].join() threads2[i].join() self.assertFalse(lock1.is_locked) self.assertFalse(lock2.is_locked) return None def test_timeout(self): """ Tests if the lock raises a TimeOut error, when it can not be acquired. """ lock1 = self.LOCK_TYPE(self.LOCK_PATH) lock2 = self.LOCK_TYPE(self.LOCK_PATH) # Acquire lock 1. lock1.acquire() self.assertTrue(lock1.is_locked) self.assertFalse(lock2.is_locked) # Try to acquire lock 2. self.assertRaises(filelock.Timeout, lock2.acquire, timeout=1) # FIXME (Filelock) self.assertFalse(lock2.is_locked) self.assertTrue(lock1.is_locked) # Release lock 1. lock1.release() self.assertFalse(lock1.is_locked) self.assertFalse(lock2.is_locked) return None def test_default_timeout(self): """ Test if the default timeout parameter works. """ lock1 = self.LOCK_TYPE(self.LOCK_PATH) lock2 = self.LOCK_TYPE(self.LOCK_PATH, timeout = 1) self.assertEqual(lock2.timeout, 1) # Acquire lock 1. lock1.acquire() self.assertTrue(lock1.is_locked) self.assertFalse(lock2.is_locked) # Try to acquire lock 2. self.assertRaises(filelock.Timeout, lock2.acquire) # FIXME (SoftFileLock) self.assertFalse(lock2.is_locked) self.assertTrue(lock1.is_locked) lock2.timeout = 0 self.assertEqual(lock2.timeout, 0) self.assertRaises(filelock.Timeout, lock2.acquire) self.assertFalse(lock2.is_locked) self.assertTrue(lock1.is_locked) # Release lock 1. lock1.release() self.assertFalse(lock1.is_locked) self.assertFalse(lock2.is_locked) return None def test_context(self): """ Tests, if the filelock is released, when an exception is thrown in a with-statement. """ lock = self.LOCK_TYPE(self.LOCK_PATH) try: with lock as lock1: self.assertIs(lock, lock1) self.assertTrue(lock.is_locked) raise Exception() except: self.assertFalse(lock.is_locked) return None def test_context1(self): """ The same as *test_context1()*, but uses the *acquire()* method. """ lock = self.LOCK_TYPE(self.LOCK_PATH) try: with lock.acquire() as lock1: self.assertIs(lock, lock1) self.assertTrue(lock.is_locked) raise Exception() except: self.assertFalse(lock.is_locked) return None @unittest.skipIf(hasattr(sys, 'pypy_version_info'), 'del() does not trigger GC in PyPy') def test_del(self): """ Tests, if the lock is released, when the object is deleted. """ lock1 = self.LOCK_TYPE(self.LOCK_PATH) lock2 = self.LOCK_TYPE(self.LOCK_PATH) # Acquire lock 1. lock1.acquire() self.assertTrue(lock1.is_locked) self.assertFalse(lock2.is_locked) # Try to acquire lock 2. self.assertRaises(filelock.Timeout, lock2.acquire, timeout = 1) # FIXME (SoftFileLock) # Delete lock 1 and try to acquire lock 2 again. del lock1 lock2.acquire() self.assertTrue(lock2.is_locked) lock2.release() return None class FileLockTest(BaseTest, unittest.TestCase): """ Tests the hard file lock, which is available on the current platform. """ LOCK_TYPE = filelock.FileLock LOCK_PATH = "test.lock" class SoftFileLockTest(BaseTest, unittest.TestCase): """ Tests the soft file lock, which is always available. """ LOCK_TYPE = filelock.SoftFileLock LOCK_PATH = "test.softlock" def test_cleanup(self): """ Tests if the lock file is removed after use. """ lock = self.LOCK_TYPE(self.LOCK_PATH) with lock: self.assertTrue(os.path.exists(self.LOCK_PATH)) self.assertFalse(os.path.exists(self.LOCK_PATH)) return None if __name__ == "__main__": unittest.main()