2 # Copyright (c) 2000 - 2016 Samsung Electronics Co., Ltd. All rights reserved.
5 # @author Chulwoo Shin <cw1.shin@samsung.com>
7 # Licensed under the Apache License, Version 2.0 (the "License");
8 # you may not use this file except in compliance with the License.
9 # You may obtain a copy of the License at
11 # http://www.apache.org/licenses/LICENSE-2.0
13 # Unless required by applicable law or agreed to in writing, software
14 # distributed under the License is distributed on an "AS IS" BASIS,
15 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 # See the License for the specific language governing permissions and
17 # limitations under the License.
28 class FileLockException(Exception):
30 class FileLock(object):
31 def __init__(self, file_name, timeout=10, delay=.05):
32 self.is_locked = False
33 self.lockfile = os.path.join(os.getcwd(), "%s.lock" % file_name)
34 self.file_name = file_name
35 self.timeout = timeout
38 self.fd = os.open(self.lockfile, os.O_CREAT|os.O_EXCL|os.O_RDWR)
43 os.unlink(self.lockfile)
44 self.is_locked = False
46 if not self.is_locked:
49 def __exit__(self, type, value, traceback):
58 except OSError as err:
59 if err.errno != errno.EEXIST:
62 def write(path, data):
64 make_dirs(os.path.dirname(path))
65 with(open(path, 'w')) as f:
68 def write_json_flock(path, data):
70 make_dirs(os.path.dirname(path))
72 with(open(path, 'w')) as f:
73 f.write(json.dumps(data))
75 if e.errno != errno.EEXIST:
83 except ValueError as ve:
85 except (OSError, IOError) as e:
89 def decompress_gzip(intput_path, output_path):
90 with(gzip.open(intput_path, 'rb')) as fobj:
91 f = open(output_path, 'wb')
96 def copyfile_flock(src, dest):
100 shutil.copy(src, dest)
102 if e.errno != errno.EEXIST:
107 def copyfile(src, dst, filename=None):
108 abs_dst=os.path.abspath(os.path.expanduser(dst))
111 abs_dst = os.path.join(abs_dst, filename)
112 shutil.copy(src, abs_dst)
115 return os.path.join(abs_dst, os.path.basename(src))