1 # -*- coding: utf-8 -*-
3 # Copyright (c) 2009 Evan Fosmark
4 # Copyright (c) 2014 Jack Kaliko <kaliko@azylum.org>
6 # This program is free software: you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation, either version 3 of the License, or
9 # (at your option) any later version.
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 # GNU General Public License for more details.
16 # You should have received a copy of the GNU General Public License
17 # along with this program. If not, see <http://www.gnu.org/licenses/>.
21 # https://github.com/dmfrey/FileLock
23 Plain file lock to une in context:
24 >>> with FileLock('/path/to/file/to/write'):
25 >>> # a lock file is maintain within the scope of this context:
26 >>> # /path/to/file/to/write.lock
27 >>> ... # process file writing
34 class FileLockException(Exception):
35 """FileLock Exception"""
39 """ A plain file lock whit context-manager"""
41 def __init__(self, file_name, timeout=10, delay=.05):
44 Setup timeout and the delay.
47 self.is_locked = False
48 dirname = os.path.dirname(file_name)
49 self.lockfile = os.path.join(dirname, '{0}.lock'.format(file_name))
50 self.file_name = file_name
51 self.timeout = timeout
55 """Acquire the lock, if possible.
57 start_time = time.time()
60 self.filedsc = os.open(self.lockfile,
61 os.O_CREAT|os.O_EXCL|os.O_RDWR)
63 except OSError as err:
64 if err.errno != errno.EEXIST:
66 if (time.time() - start_time) >= self.timeout:
67 raise FileLockException('Timeout occured.')
68 time.sleep(self.delay)
75 os.close(self.filedsc)
76 os.unlink(self.lockfile)
77 self.is_locked = False
80 """start of the with statement.
82 if not self.is_locked:
86 def __exit__(self, type, value, traceback):
87 """end of the with statement