本文整理汇总了Python中lockfile.LockFile.is_locked方法的典型用法代码示例。如果您正苦于以下问题:Python LockFile.is_locked方法的具体用法?Python LockFile.is_locked怎么用?Python LockFile.is_locked使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类lockfile.LockFile
的用法示例。
在下文中一共展示了LockFile.is_locked方法的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: ReadTestCase
# 需要导入模块: from lockfile import LockFile [as 别名]
# 或者: from lockfile.LockFile import is_locked [as 别名]
def ReadTestCase( resourcefile ) :
list = []
row_index = 0
from lockfile import LockFile
lock = LockFile(resourcefile)
lockid = lock.is_locked()
print lockid
for a in xrange(1, 2):
if lockid == False:
lock.acquire()
print "I have locked Resource File"
break
else:
time.sleep (10)
lockid = lock.is_locked()
rb = open_workbook(resourcefile)
r_sheet = rb.sheet_by_index(0)
wb = copy(rb)
w_sheet = wb.get_sheet(0)
keys = [r_sheet.cell(0, col_index).value for col_index in xrange(r_sheet.ncols)]
j = r_sheet.nrows
q = r_sheet.ncols
print col_index
while row_index < j:
d = {keys[col_index]: r_sheet.cell(row_index, col_index).value for col_index in xrange(r_sheet.ncols)}
temp = ""
if ( d['Execution'] == "yes") :
temp = d['TC Name']
print temp
list.append(temp)
wb.save(resourcefile)
row_index = row_index + 1
lock.release()
return list
示例2: GetPassword
# 需要导入模块: from lockfile import LockFile [as 别名]
# 或者: from lockfile.LockFile import is_locked [as 别名]
def GetPassword( resourcefile , list ) :
count = 0
pwd = []
rb = open_workbook(resourcefile)
r_sheet = rb.sheet_by_index(0)
from lockfile import LockFile
lock = LockFile(resourcefile)
lockid = lock.is_locked()
print lockid
for a in xrange(1, 10):
if lockid == False:
lock.acquire()
print "I have locked Resource File"
break
else:
time.sleep (10)
lockid = lock.is_locked()
wb = copy(rb)
w_sheet = wb.get_sheet(0)
keys = [r_sheet.cell(0, col_index).value for col_index in xrange(r_sheet.ncols)]
for row_index in xrange(1, r_sheet.nrows):
d = {keys[col_index]: r_sheet.cell(row_index, col_index).value
for col_index in xrange(r_sheet.ncols)}
if ( d['IP'] in list) :
count = count + 1
pwd = d['Password']
wb.save(resourcefile)
lock.release()
if(count == len(list)+1) :
break
return pwd
示例3: sync_folder
# 需要导入模块: from lockfile import LockFile [as 别名]
# 或者: from lockfile.LockFile import is_locked [as 别名]
def sync_folder(self):
encrypted_folder_lock = LockFile(self.encrypted_folder)
if encrypted_folder_lock.is_locked():
self.info("Acquiring the lock of encrypted folder...")
with encrypted_folder_lock:
plain_folder_lock = LockFile(self.plain_folder)
if plain_folder_lock.is_locked():
self.info("Acquiring the lock of plaintext folder...")
with plain_folder_lock:
self._do_sync_folder()
示例4: run_each_job
# 需要导入模块: from lockfile import LockFile [as 别名]
# 或者: from lockfile.LockFile import is_locked [as 别名]
def run_each_job(conf_dict, uploadurl):
if not os.path.exists(CYCLIC_PATH):
os.makedirs(CYCLIC_PATH, 02775)
# split each cyclic jobs
cyclic_jobs_path = get_cyclic_jobs(conf_dict)
split_job_params = ' '.join(cyclic_jobs_path)
split_cmd = "%s split -j %s -o %s" % (SRC+'/bin/pst', split_job_params, CYCLIC_PATH)
split_output = subprocess.check_output(split_cmd, shell=True)
split_jobs_path = [split_file.split(' => ')[1] for split_file in split_output.split('\n') if split_file]
# run each splited jobs
sync_dir = conf_dict.get('sync', {}).get('dir')
sync_list = conf_dict.get('sync', {}).get('jobs')
wait_timeout = conf_dict.get('sync', {}).get('timeout')
if sync_dir and sync_list and 'all' in sync_list:
try:
lock = LockFile(sync_dir + os.sep + 'all')
lock.acquire()
for unit_jobfile in split_jobs_path:
run_cmd = "%s run -j %s -u %s" % (SRC + '/bin/pst', unit_jobfile, uploadurl)
run_shell_cmd(run_cmd)
print("Remove: %s" % unit_jobfile)
os.remove(unit_jobfile)
lock.release()
except KeyboardInterrupt:
if lock.is_locked():
lock.release()
raise
else:
for unit_jobfile in split_jobs_path:
run_cmd = "%s run -j %s -u %s" % (SRC + '/bin/pst', unit_jobfile, uploadurl)
# add lock to sync there, e.g. run doker and host test same time
testcase_name = common.load_conf(unit_jobfile).get('testcase')
if sync_dir and sync_list and testcase_name in sync_list:
lock = LockFile(sync_dir + os.sep + testcase_name)
try:
lock.acquire(timeout=wait_timeout)
run_shell_cmd(run_cmd)
lock.release()
except LockTimeout as e:
print e
except KeyboardInterrupt:
if lock.is_locked():
lock.release()
raise
else:
run_shell_cmd(run_cmd)
print("Remove: %s" % unit_jobfile)
os.remove(unit_jobfile)
示例5: PythonAllocate
# 需要导入模块: from lockfile import LockFile [as 别名]
# 或者: from lockfile.LockFile import is_locked [as 别名]
def PythonAllocate ( num , resourcefile , list ) :
IPList1 = ""
count = 0
row_index = 0
from lockfile import LockFile
lock = LockFile(resourcefile)
lockid = lock.is_locked()
print lockid
for a in xrange(1, 2):
if lockid == False:
lock.acquire()
print "I have locked Resource File"
break
else:
time.sleep (10)
lockid = lock.is_locked()
rb = open_workbook(resourcefile)
r_sheet = rb.sheet_by_index(0)
wb = copy(rb)
w_sheet = wb.get_sheet(0)
keys = [r_sheet.cell(0, col_index).value for col_index in xrange(r_sheet.ncols)]
j = r_sheet.nrows
while row_index < j:
d = {keys[col_index]: r_sheet.cell(row_index, col_index).value for col_index in xrange(r_sheet.ncols)}
length = len(list)
if ( d['STATUS'] == "free") :
a = " "
w_sheet.write(row_index,col_index-2,"allocated")
wb.save(resourcefile)
lock.release()
count = count + 1
resourcename = d['IP']
string1 = str(list)+ a + str(resourcename)
string2 = string1.strip()
print string2
list = string2.split( )
length = len(list)
print list
j = 1
row_index = row_index + 1
print "list",list
if ( list == "" ) :
lock.release()
return list
示例6: _download_rpm
# 需要导入模块: from lockfile import LockFile [as 别名]
# 或者: from lockfile.LockFile import is_locked [as 别名]
def _download_rpm(self, nvr, arch):
if nvr is None or arch is None:
raise ValueError("Invalid option passed to connector")
filename = '%s.%s.rpm' % (nvr, arch)
file_path = os.path.split(filename)
if file_path[0] != '':
raise ValueError("Nvr can not contain path elements")
if len(arch.split('/')) != 1 or os.path.split(arch)[0] != '':
raise ValueError("Arch can not contain path elements")
rpm_file_path = os.path.join(self._rpm_cache, filename)
if os.path.exists(rpm_file_path):
return rpm_file_path
lockfile = LockFile(file_path)
if lockfile.is_locked():
# block until the lock is released and then assume other
# thread was successful
lockfile.acquire()
lockfile.release()
return rpm_file_path
# acquire the lock and release when done
lockfile.acquire()
try:
info = self.call('getBuild', {'buildInfo': nvr})
if info is None:
return {'error': 'No such build (%s)' % filename}
if not os.path.exists(self._rpm_cache):
os.mkdir(self._rpm_cache,)
url = '%s/%s/%s/%s/%s/%s' % (
self._koji_pkg_url, info['name'], info['version'],
info['release'], arch, filename)
url_file = grabber.urlopen(url, text=filename)
out = os.open(
rpm_file_path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0666)
try:
while 1:
buf = url_file.read(4096)
if not buf:
break
os.write(out, buf)
except Exception as e:
raise e
finally:
os.close(out)
url_file.close()
finally:
lockfile.release()
return rpm_file_path
示例7: State
# 需要导入模块: from lockfile import LockFile [as 别名]
# 或者: from lockfile.LockFile import is_locked [as 别名]
class State(object):
def __init__(self, path=None, lock=False):
self.path = path
self.lock = lock
if not self.path:
self.path = join(util.get_home_dir(), "appstate.json")
self._state = {}
self._prev_state = {}
self._lockfile = None
def __enter__(self):
try:
self._lock_state_file()
if isfile(self.path):
self._state = util.load_json(self.path)
except exception.PlatformioException:
self._state = {}
self._prev_state = deepcopy(self._state)
return self._state
def __exit__(self, type_, value, traceback):
if self._prev_state != self._state:
with open(self.path, "w") as fp:
if "dev" in __version__:
json.dump(self._state, fp, indent=4)
else:
json.dump(self._state, fp)
self._unlock_state_file()
def _lock_state_file(self):
if not self.lock:
return
self._lockfile = LockFile(self.path)
if self._lockfile.is_locked() and \
(time() - getmtime(self._lockfile.lock_file)) > 10:
self._lockfile.break_lock()
try:
self._lockfile.acquire()
except LockFailed:
raise exception.PlatformioException(
"The directory `{0}` or its parent directory is not owned by "
"the current user and PlatformIO can not store configuration "
"data. \nPlease check the permissions and owner of that "
"directory. Otherwise, please remove manually `{0}` "
"directory and PlatformIO will create new from the current "
"user.".format(dirname(self.path)))
def _unlock_state_file(self):
if self._lockfile:
self._lockfile.release()
示例8: lock
# 需要导入模块: from lockfile import LockFile [as 别名]
# 或者: from lockfile.LockFile import is_locked [as 别名]
def lock(self):
"""
Method used for acquiring a lock using the lockfile module.
"""
lock = LockFile(self.lockfile)
# check if it's locked
if lock.is_locked():
# Note that lock.i_am_locking() could be True, so
# this apporach is not really efficient from a threading
# point of view. However, we must be consistent with
# MemcachedCacheQueue's behavior.
return False
# else we can attempt to acquire a lock
# we don't want this to fail silently
# so we set timeout=0
lock.acquire(timeout=0)
return True
示例9: State
# 需要导入模块: from lockfile import LockFile [as 别名]
# 或者: from lockfile.LockFile import is_locked [as 别名]
class State(object):
def __init__(self, path=None, lock=False):
self.path = path
self.lock = lock
if not self.path:
self.path = join(get_home_dir(), "appstate.json")
self._state = {}
self._prev_state = {}
self._lockfile = None
def __enter__(self):
try:
self._lock_state_file()
if isfile(self.path):
with open(self.path, "r") as fp:
self._state = json.load(fp)
except ValueError:
self._state = {}
self._prev_state = deepcopy(self._state)
return self._state
def __exit__(self, type_, value, traceback):
if self._prev_state != self._state:
with open(self.path, "w") as fp:
if "dev" in __version__:
json.dump(self._state, fp, indent=4)
else:
json.dump(self._state, fp)
self._unlock_state_file()
def _lock_state_file(self):
if not self.lock:
return
self._lockfile = LockFile(self.path)
if (self._lockfile.is_locked() and
(time() - getmtime(self._lockfile.lock_file)) > 10):
self._lockfile.break_lock()
self._lockfile.acquire()
def _unlock_state_file(self):
if self._lockfile:
self._lockfile.release()
示例10: ContentCache
# 需要导入模块: from lockfile import LockFile [as 别名]
# 或者: from lockfile.LockFile import is_locked [as 别名]
class ContentCache(object):
def __init__(self, cache_dir=None):
self.cache_dir = None
self._db_path = None
self._lockfile = None
if not get_setting("enable_cache"):
return
self.cache_dir = cache_dir or join(util.get_home_dir(), ".cache")
self._db_path = join(self.cache_dir, "db.data")
def __enter__(self):
if not self._db_path or not isfile(self._db_path):
return self
self.delete()
return self
def __exit__(self, type_, value, traceback):
pass
def _lock_dbindex(self):
if not self.cache_dir:
os.makedirs(self.cache_dir)
self._lockfile = LockFile(self.cache_dir)
if self._lockfile.is_locked() and \
(time() - getmtime(self._lockfile.lock_file)) > 10:
self._lockfile.break_lock()
try:
self._lockfile.acquire()
except LockFailed:
return False
return True
def _unlock_dbindex(self):
if self._lockfile:
self._lockfile.release()
return True
def get_cache_path(self, key):
assert len(key) > 3
return join(self.cache_dir, key[-2:], key)
@staticmethod
def key_from_args(*args):
h = hashlib.md5()
for data in args:
h.update(str(data))
return h.hexdigest()
def get(self, key):
cache_path = self.get_cache_path(key)
if not isfile(cache_path):
return None
with open(cache_path, "rb") as fp:
data = fp.read()
if data and data[0] in ("{", "["):
return json.loads(data)
return data
def set(self, key, data, valid):
cache_path = self.get_cache_path(key)
if isfile(cache_path):
self.delete(key)
if not data:
return
if not isdir(self.cache_dir):
os.makedirs(self.cache_dir)
tdmap = {"s": 1, "m": 60, "h": 3600, "d": 86400}
assert valid.endswith(tuple(tdmap.keys()))
expire_time = int(time() + tdmap[valid[-1]] * int(valid[:-1]))
if not self._lock_dbindex():
return False
if not isdir(dirname(cache_path)):
os.makedirs(dirname(cache_path))
with open(cache_path, "wb") as fp:
if isinstance(data, (dict, list)):
json.dump(data, fp)
else:
fp.write(str(data))
with open(self._db_path, "a") as fp:
fp.write("%s=%s\n" % (str(expire_time), cache_path))
return self._unlock_dbindex()
def delete(self, keys=None):
""" Keys=None, delete expired items """
if not keys:
keys = []
if not isinstance(keys, list):
keys = [keys]
paths_for_delete = [self.get_cache_path(k) for k in keys]
found = False
newlines = []
#.........这里部分代码省略.........
示例11: is_locked
# 需要导入模块: from lockfile import LockFile [as 别名]
# 或者: from lockfile.LockFile import is_locked [as 别名]
def is_locked(datadir):
"""
Return True if this datadir is locked for migrations
"""
lockfile = LockFile(datadir + '/.migration_lock')
return lockfile.is_locked()
示例12: mirror_main
# 需要导入模块: from lockfile import LockFile [as 别名]
# 或者: from lockfile.LockFile import is_locked [as 别名]
def mirror_main():
"""Entry point."""
signal.signal(signal.SIGINT, lock_ctrl_c_handler)
parser = argparse.ArgumentParser()
parser.add_argument('-H', '--host', required=True)
parser.add_argument('-P', '--port', type=int, default=22)
parser.add_argument('-c', '--netrc-path', default=expanduser('~/.netrc'))
parser.add_argument('-r', '--resume', action='store_true',
help='Resume incomplete files (experimental)')
parser.add_argument('-T', '--move-to', required=True)
parser.add_argument('-L', '--label', default='Seeding')
parser.add_argument('-d', '--debug', action='store_true')
parser.add_argument('-v', '--verbose', action='store_true')
parser.add_argument('-s', '--syslog', action='store_true')
parser.add_argument('--no-preserve-permissions', action='store_false')
parser.add_argument('--no-preserve-times', action='store_false')
parser.add_argument('--max-retries', type=int, default=10)
parser.add_argument('remote_dir', metavar='REMOTEDIR', nargs=1)
parser.add_argument('local_dir', metavar='LOCALDIR', nargs=1)
args = parser.parse_args()
log = get_logger('xirvik',
verbose=args.verbose,
debug=args.debug,
syslog=args.syslog)
if args.debug:
logs_to_follow = (
'requests',
)
for name in logs_to_follow:
_log = logging.getLogger(name)
formatter = logging.Formatter('%(asctime)s - %(name)s - '
'%(levelname)s - %(message)s')
channel = logging.StreamHandler(sys.stderr)
_log.setLevel(logging.DEBUG)
channel.setLevel(logging.DEBUG)
channel.setFormatter(formatter)
_log.addHandler(channel)
local_dir = realpath(args.local_dir[0])
user, _, password = netrc(args.netrc_path).authenticators(args.host)
sftp_host = 'sftp://{user:s}@{host:s}'.format(
user=user,
host=args.host,
)
lf_hash = hashlib.sha256(json.dumps(
args._get_kwargs()).encode('utf-8')).hexdigest()
lf_path = path_join(gettempdir(), 'xirvik-mirror-{}'.format(lf_hash))
log.debug('Acquiring lock at {}.lock'.format(lf_path))
_lock = LockFile(lf_path)
if _lock.is_locked():
psax = [x for x in
sp.check_output(['ps', 'ax']).decode('utf-8').split('\n')
if sys.argv[0] in x]
if len(psax) == 1:
log.info('Breaking lock')
_lock.break_lock()
_lock.acquire()
log.info('Lock acquired')
log.debug('Local directory to sync to: {}'.format(local_dir))
log.debug('Read user and password from netrc file')
log.debug('SFTP URI: {}'.format(sftp_host))
client = ruTorrentClient(args.host,
user,
password,
max_retries=args.max_retries)
assumed_path_prefix = '/torrents/{}'.format(user)
look_for = '{}/{}/'.format(assumed_path_prefix, args.remote_dir[0])
move_to = '{}/{}'.format(assumed_path_prefix, args.move_to)
names = {}
log.debug('Full completed directory path name: {}'.format(look_for))
log.debug('Moving finished torrents to: {}'.format(move_to))
log.info('Getting current torrent information (ruTorrent)')
try:
torrents = client.list_torrents()
except requests.exceptions.ConnectionError as e:
# Assume no Internet connection at this point
log.error('Failed to connect: {}'.format(e))
try:
_lock.release()
except NotLocked:
pass
cleanup_and_exit(1)
for hash, v in torrents.items():
if not v[TORRENT_PATH_INDEX].startswith(look_for):
continue
bn = basename(v[TORRENT_PATH_INDEX])
names[bn] = (hash, v[TORRENT_PATH_INDEX],)
log.info('Completed torrent "{}" found with hash {}'.format(bn, hash,))
#.........这里部分代码省略.........