本文整理汇总了Python中lockfile.LockFile.acquire方法的典型用法代码示例。如果您正苦于以下问题:Python LockFile.acquire方法的具体用法?Python LockFile.acquire怎么用?Python LockFile.acquire使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类lockfile.LockFile
的用法示例。
在下文中一共展示了LockFile.acquire方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: generateQueryAndQueryVectorMap
# 需要导入模块: from lockfile import LockFile [as 别名]
# 或者: from lockfile.LockFile import acquire [as 别名]
def generateQueryAndQueryVectorMap(line_tmp):
sentencevector = []
# print "Number of Records Left:\t" + str(corpuscount - tmpcount)
query = line_tmp.lower()
component_word = query.split(' ')
for one_word in component_word:
if redis_handle.exists(one_word):
vector_tmp = redis_handle.get(one_word)
vector_final = normalize_redis_vector(vector_tmp)
sentencevector.append(vector_final)
#indexnum = vocab_dict.get(one_word)
#sentencevector.append((repvector[indexnum]).tolist())
else:
sentencevector.append([float(0)] * vector_size)
l = numpy.array(sentencevector)
# Centroid Calculation - each sentence.
# Sums up all vectors (columns) and generates a final list (1D)of size vector_size
lmt = numpy.array(l.sum(axis=0, dtype=numpy.float32)).tolist()
if (lmt != 0.0):
# Averages the vectors based on the number of words in each sentence.
query_vector = [x / len(component_word) for x in lmt]
else:
query_vector = [float(0)] * vector_size
filename = getRandomOutputFilename()
lock = LockFile(filename)
lock.acquire()
# Open a file handle to the lock file
fh = open(filename, 'w')
fh.write(str(query)+"\t")
for item in query_vector:
fh.write("%s " % str(item))
fh.close()
lock.release()
示例2: main
# 需要导入模块: from lockfile import LockFile [as 别名]
# 或者: from lockfile.LockFile import acquire [as 别名]
def main(username, password):
# Ignore error, logging set up in logging utils
from . import logging_utils
from .navigation import Leifur
from .config import get_config, set_config, get_config_from_user
lock = LockFile('/tmp/spoppy')
try:
# Try for 5s to acquire the lock
lock.acquire(5)
except LockTimeout:
click.echo('Could not acquire lock, is spoppy running?')
click.echo(
'If you\'re sure that spoppy is not running, '
'try removing the lock file %s' % lock.lock_file
)
else:
if username and password:
set_config(username, password)
else:
username, password = get_config()
if not (username and password):
username, password = get_config_from_user()
navigator = None
try:
navigator = Leifur(username, password)
navigator.start()
finally:
if navigator:
navigator.shutdown()
logger.debug('Finally, bye!')
finally:
if lock.i_am_locking():
lock.release()
示例3: write_ht_sensor_log
# 需要导入模块: from lockfile import LockFile [as 别名]
# 或者: from lockfile.LockFile import acquire [as 别名]
def write_ht_sensor_log(sensor_ht_read_temp_c, sensor_ht_read_hum, sensor_ht_dewpt_c, sensor):
if not os.path.exists(lock_directory):
os.makedirs(lock_directory)
lock = LockFile(sensor_ht_log_lock_path)
while not lock.i_am_locking():
try:
logging.debug("[Write Sensor Log] Acquiring Lock: %s", lock.path)
lock.acquire(timeout=60) # wait up to 60 seconds
except:
logging.warning("[Write Sensor Log] Breaking Lock to Acquire: %s", lock.path)
lock.break_lock()
lock.acquire()
logging.debug("[Write Sensor Log] Gained lock: %s", lock.path)
try:
with open(sensor_ht_log_file_tmp, "ab") as sensorlog:
sensorlog.write('{0} {1:.1f} {2:.1f} {3:.1f} {4:d}\n'.format(
datetime.datetime.now().strftime("%Y/%m/%d-%H:%M:%S"),
sensor_ht_read_temp_c[sensor], sensor_ht_read_hum[sensor], sensor_ht_dewpt_c[sensor], sensor))
logging.debug("[Write Sensor Log] Data appended to %s", sensor_ht_log_file_tmp)
except:
logging.warning("[Write Sensor Log] Unable to append data to %s", sensor_ht_log_file_tmp)
logging.debug("[Write Sensor Log] Removing lock: %s", lock.path)
lock.release()
示例4: run
# 需要导入模块: from lockfile import LockFile [as 别名]
# 或者: from lockfile.LockFile import acquire [as 别名]
def run(self):
self.set_arguments()
args = self.parser.parse_args()
if args.verbose:
set_logging(level=logging.DEBUG)
elif args.quiet:
set_logging(level=logging.WARNING)
else:
set_logging(level=logging.INFO)
lock = LockFile(os.path.join(Utils.getRoot(), LOCK_FILE))
try:
lock.acquire(timeout=-1)
args.func(args)
except AttributeError:
if hasattr(args, 'func'):
raise
else:
self.parser.print_help()
except KeyboardInterrupt:
pass
except AlreadyLocked:
logger.error("Could not proceed - there is probably another instance of Atomic App running on this machine.")
except Exception as ex:
if args.verbose:
raise
else:
logger.error("Exception caught: %s", repr(ex))
logger.error(
"Run the command again with -v option to get more information.")
finally:
if lock.i_am_locking():
lock.release()
示例5: GetPassword
# 需要导入模块: from lockfile import LockFile [as 别名]
# 或者: from lockfile.LockFile import acquire [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
示例6: ReadTestCase
# 需要导入模块: from lockfile import LockFile [as 别名]
# 或者: from lockfile.LockFile import acquire [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
示例7: run
# 需要导入模块: from lockfile import LockFile [as 别名]
# 或者: from lockfile.LockFile import acquire [as 别名]
def run(self):
alerts = []
if not os.path.exists(COLLECTD_FILE):
return alerts
lock = LockFile(COLLECTD_FILE)
while not lock.i_am_locking():
try:
lock.acquire(timeout=5)
except LockTimeout:
return alerts
with open(COLLECTD_FILE, 'rb') as f:
try:
data = pickle.loads(f.read())
except:
data = {}
lock.release()
for k, v in list(data.items()):
if v['Severity'] == 'WARNING':
l = Alert.WARN
else:
l = Alert.CRIT
if k == 'ctl-ha/disk_octets':
msg = "CTL HA link is actively used, check initiators connectivity"
else:
msg = k
alerts.append(Alert(l, msg))
return alerts
示例8: write_target_runtime_properties_to_file
# 需要导入模块: from lockfile import LockFile [as 别名]
# 或者: from lockfile.LockFile import acquire [as 别名]
def write_target_runtime_properties_to_file(required_keys, prefixed_keys=None, need_suffix=None):
try:
current_runtime_folder = constants.default_path_to_runtime_folder
current_instance_key = "{0}{1}".format(ctx.source.node.id, ctx.source.instance.id)
current_runtime_file_path = "{0}{1}".format(current_runtime_folder, current_instance_key)
ctx.logger.info("current_runtime_file_path is {0}".format(current_runtime_file_path))
lock = LockFile(current_runtime_file_path)
lock.acquire()
ctx.logger.info("{} is locked".format(lock.path))
with open(current_runtime_file_path, 'a') as f:
for curr_runtime_property in ctx.target.instance.runtime_properties:
orig_runtime_property = curr_runtime_property
if required_keys and curr_runtime_property in required_keys:
if need_suffix and (curr_runtime_property in need_suffix):
curr_runtime_property = "{0}{1}{2}".format(curr_runtime_property, ctx.source.node.id, ctx.source.instance.id)
ctx.logger.info("curr_runtime_property is {0}".format(curr_runtime_property))
current_line = "{0}={1}\n".format(curr_runtime_property, ctx.target.instance.runtime_properties[orig_runtime_property])
f.write(current_line)
else:
if prefixed_keys is not None:
for curr_prefixed_key in prefixed_keys:
if curr_runtime_property.startswith(curr_prefixed_key):
current_line = "{0}={1}\n".format(curr_runtime_property, ctx.target.instance.runtime_properties[curr_runtime_property])
f.write(current_line)
f.close()
except:
ctx.logger.info("Failures while locking or using {}".format(current_runtime_file_path))
lock.release()
raise NonRecoverableError("Failures while locking or using {}".format(current_runtime_file_path))
lock.release()
ctx.logger.info("{} is released".format(current_runtime_file_path))
示例9: restart
# 需要导入模块: from lockfile import LockFile [as 别名]
# 或者: from lockfile.LockFile import acquire [as 别名]
def restart(): # this really could be health
lock = None
try:
lock = LockFile('json/health.json', 'r')
lock.acquire()
with open('json/health.json', 'r') as json_file:
data = json.load(json_file, encoding='utf-8')
if request.method == 'POST':
status = request.args.get('status', type=str)
if status is None:
print 'no status given, defaults to true'
status = 'true'
data['restart'] = status
with open('json/health.json', 'w') as json_file:
json_file.write(json.dumps(data))
lock.release()
return 'restart set to %s' % status
if request.method == 'GET':
lock.release()
return data['restart']
except IOError:
if lock is not None:
lock.release()
return Messages.inventoryNotFound()
示例10: run
# 需要导入模块: from lockfile import LockFile [as 别名]
# 或者: from lockfile.LockFile import acquire [as 别名]
def run(self):
alerts = []
if not os.path.exists(SMART_FILE):
return alerts
lock = LockFile(SMART_FILE)
while not lock.i_am_locking():
try:
lock.acquire(timeout=5)
except LockTimeout:
return alerts
with open(SMART_FILE, 'rb') as f:
try:
data = pickle.loads(f.read())
except:
data = {}
msg = ''
for msgs in data.itervalues():
if not msgs:
continue
msg += '<br />\n'.join(msgs)
if msg:
alerts.append(Alert(Alert.CRIT, msg))
lock.release()
return alerts
示例11: store
# 需要导入模块: from lockfile import LockFile [as 别名]
# 或者: from lockfile.LockFile import acquire [as 别名]
def store(email,nickname,number,rate,strs,regressions):
# User-entered data hits the filesystem here.
if not validate_email(email):
return
newcontrib = [ bleach.clean(email),
bleach.clean(nickname),
bleach.clean(number),
bleach.clean(rate),
bleach.clean(strs),
bleach.clean(regressions)]
lock = LockFile("/var/local/bz-triage/contributors.cfg")
lock.acquire()
try:
contributors = json.load(open("/var/local/bz-triage/contributors.cfg"))
except:
logging.info("Failed to open the file...")
contributors = list()
for existing in contributors:
if existing[0] == newcontrib[0]:
contributors.remove(existing)
contributors.append( newcontrib )
with open("/var/local/bz-triage/contributors.cfg", 'w') as outfile:
json.dump(contributors, outfile)
lock.release()
示例12: locked_cache_dir
# 需要导入模块: from lockfile import LockFile [as 别名]
# 或者: from lockfile.LockFile import acquire [as 别名]
def locked_cache_dir(config, cache_key, timeout=900, tag=None):
if LockFile is DummyLock:
cache_key = cache_key + os.environ.get('PYTEST_XDIST_WORKER', '')
base_dir = config.cache.makedir(cache_key)
lockfile = join(six.text_type(base_dir), 'lock')
cache_dir = join(six.text_type(base_dir), 'cache')
lock = LockFile(lockfile)
lock.acquire(timeout=timeout)
try:
# Clear cache dir contents if it was generated with different
# asv version
tag_fn = join(six.text_type(base_dir), 'tag.json')
tag_content = [asv.__version__, repr(tag)]
if os.path.isdir(cache_dir):
try:
if util.load_json(tag_fn) != tag_content:
raise ValueError()
except (IOError, ValueError, util.UserError):
shutil.rmtree(cache_dir)
if not os.path.isdir(cache_dir):
os.makedirs(cache_dir)
yield cache_dir
util.write_json(tag_fn, tag_content)
finally:
lock.release()
示例13: run
# 需要导入模块: from lockfile import LockFile [as 别名]
# 或者: from lockfile.LockFile import acquire [as 别名]
def run(self):
alerts = []
if not os.path.exists(SMART_FILE):
return alerts
lock = LockFile(SMART_FILE)
while not lock.i_am_locking():
try:
lock.acquire(timeout=5)
except LockTimeout:
return alerts
with open(SMART_FILE, 'rb') as f:
try:
data = pickle.loads(f.read())
except:
data = {}
for msgs in data.itervalues():
if not msgs:
continue
for msg in msgs:
if msg is None:
continue
alerts.append(Alert(Alert.CRIT, msg, hardware=True))
lock.release()
return alerts
示例14: main
# 需要导入模块: from lockfile import LockFile [as 别名]
# 或者: from lockfile.LockFile import acquire [as 别名]
def main():
lock = LockFile(SMART_FILE)
while not lock.i_am_locking():
try:
lock.acquire(timeout=5)
except LockTimeout:
lock.break_lock()
data = {}
if os.path.exists(SMART_FILE):
with open(SMART_FILE, 'rb') as f:
try:
data = pickle.loads(f.read())
except:
pass
device = os.environ.get('SMARTD_DEVICE')
if device not in data:
data[device] = []
message = os.environ.get('SMARTD_MESSAGE')
if message not in data[device]:
data[device].append(message)
with open(SMART_FILE, 'wb') as f:
f.write(pickle.dumps(data))
lock.release()
示例15: write_relay_log
# 需要导入模块: from lockfile import LockFile [as 别名]
# 或者: from lockfile.LockFile import acquire [as 别名]
def write_relay_log(relayNumber, relaySeconds, sensor, gpio):
if not os.path.exists(lock_directory):
os.makedirs(lock_directory)
lock = LockFile(relay_log_lock_path)
while not lock.i_am_locking():
try:
logging.debug("[Write Relay Log] Acquiring Lock: %s", lock.path)
lock.acquire(timeout=60) # wait up to 60 seconds
except:
logging.warning("[Write Relay Log] Breaking Lock to Acquire: %s", lock.path)
lock.break_lock()
lock.acquire()
logging.debug("[Write Relay Log] Gained lock: %s", lock.path)
try:
with open(relay_log_file_tmp, "ab") as relaylog:
relaylog.write('{0} {1:d} {2:d} {3:d} {4:.2f}\n'.format(
datetime.datetime.now().strftime("%Y/%m/%d-%H:%M:%S"),
sensor, relayNumber, gpio, relaySeconds))
except:
logging.warning("[Write Relay Log] Unable to append data to %s", relay_log_file_tmp)
logging.debug("[Write Relay Log] Removing lock: %s", lock.path)
lock.release()