当前位置: 首页>>代码示例>>Python>>正文


Python LockFile.release方法代码示例

本文整理汇总了Python中lockfile.LockFile.release方法的典型用法代码示例。如果您正苦于以下问题:Python LockFile.release方法的具体用法?Python LockFile.release怎么用?Python LockFile.release使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在lockfile.LockFile的用法示例。


在下文中一共展示了LockFile.release方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: generateQueryAndQueryVectorMap

# 需要导入模块: from lockfile import LockFile [as 别名]
# 或者: from lockfile.LockFile import release [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()
开发者ID:ankit-cliqz,项目名称:query_embeddings,代码行数:37,代码来源:query_vector_generator_parallel_v4.py

示例2: run

# 需要导入模块: from lockfile import LockFile [as 别名]
# 或者: from lockfile.LockFile import release [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
开发者ID:dresong,项目名称:freenas,代码行数:33,代码来源:smart.py

示例3: write_ht_sensor_log

# 需要导入模块: from lockfile import LockFile [as 别名]
# 或者: from lockfile.LockFile import release [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()
开发者ID:kkelly51,项目名称:Mycodo,代码行数:29,代码来源:mycodo_log.py

示例4: main

# 需要导入模块: from lockfile import LockFile [as 别名]
# 或者: from lockfile.LockFile import release [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()
开发者ID:gunnardag,项目名称:spoppy,代码行数:37,代码来源:__init__.py

示例5: GetPassword

# 需要导入模块: from lockfile import LockFile [as 别名]
# 或者: from lockfile.LockFile import release [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
开发者ID:cidgit,项目名称:polycom_scripts,代码行数:33,代码来源:genericfun.py

示例6: write_target_runtime_properties_to_file

# 需要导入模块: from lockfile import LockFile [as 别名]
# 或者: from lockfile.LockFile import release [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))
开发者ID:anilveeramalli,项目名称:azure_windows_ext,代码行数:34,代码来源:utils.py

示例7: write_sensor_log

# 需要导入模块: from lockfile import LockFile [as 别名]
# 或者: from lockfile.LockFile import release [as 别名]
def write_sensor_log():
    config = ConfigParser.RawConfigParser()

    if not os.path.exists(lock_directory):
        os.makedirs(lock_directory)
    if not Terminate:
        lock = LockFile(sensor_lock_path)
        while not lock.i_am_locking():
            try:
                logging.info("[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.info("[Write Sensor Log] Gained lock: %s", lock.path)
        try:
            with open(sensor_log_file_tmp, "ab") as sensorlog:
                sensorlog.write('{0} {1:.1f} {2:.1f} {3:.1f}\n'.format(
                    datetime.datetime.now().strftime("%Y %m %d %H %M %S"), 
                    tempc, humidity, dewpointc))
                logging.info("[Write Sensor Log] Data appended to %s", sensor_log_file_tmp)
        except:
            logging.warning("[Write Sensor Log] Unable to append data to %s", sensor_log_file_tmp)
        logging.info("[Write Sensor Log] Removing lock: %s", lock.path)
        lock.release()
开发者ID:toddkaufmann,项目名称:Automated-Mushroom-Cultivator,代码行数:28,代码来源:mycodo.py

示例8: run

# 需要导入模块: from lockfile import LockFile [as 别名]
# 或者: from lockfile.LockFile import release [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
开发者ID:jstephanoff,项目名称:freenas,代码行数:34,代码来源:smart.py

示例9: get_auth_token

# 需要导入模块: from lockfile import LockFile [as 别名]
# 或者: from lockfile.LockFile import release [as 别名]
def get_auth_token(use_client_file=True, **kwargs):

    current_node = utils.get_node_or_source_node()
    if use_client_file:
        current_instance = utils.get_instance_or_source_instance()
        if constants.AUTH_TOKEN_VALUE in current_instance.runtime_properties:
            token = current_instance.runtime_properties[constants.AUTH_TOKEN_VALUE]
            if constants.AUTH_TOKEN_EXPIRY in current_instance.runtime_properties:
                token_expires = current_instance.runtime_properties[constants.AUTH_TOKEN_EXPIRY]
            else:
                token_expires = 0
        else:
            token = None
            token_expires = 0

        if os.path.isfile(constants.default_path_to_local_azure_token_file):
            token, token_expires = _generate_token_if_expired(constants.default_path_to_local_azure_token_file,
                                                              token, token_expires)
            return token

    try:
        config_path = current_node.properties.get(constants.path_to_azure_conf_key) or constants.default_path_to_azure_conf
        lock = LockFile(config_path)
        lock.acquire()
        token, token_expires = _get_token_from_file(config_path)
    except:
        err_message = "Failures while locking or using {}".format(config_path)
        ctx.logger.debug(err_message)
        lock.release()
        raise NonRecoverableError(err_message)

    token, token_expires = _generate_token_if_expired(config_path, token, token_expires)
    lock.release()
    return token
开发者ID:anilveeramalli,项目名称:azure_windows_ext,代码行数:36,代码来源:auth.py

示例10: locked_cache_dir

# 需要导入模块: from lockfile import LockFile [as 别名]
# 或者: from lockfile.LockFile import release [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()
开发者ID:spacetelescope,项目名称:asv,代码行数:33,代码来源:tools.py

示例11: ReadTestCase

# 需要导入模块: from lockfile import LockFile [as 别名]
# 或者: from lockfile.LockFile import release [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
开发者ID:cidgit,项目名称:polycom_scripts,代码行数:36,代码来源:genericfun.py

示例12: main

# 需要导入模块: from lockfile import LockFile [as 别名]
# 或者: from lockfile.LockFile import release [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()
开发者ID:jstephanoff,项目名称:freenas,代码行数:31,代码来源:smart_alert.py

示例13: write_relay_log

# 需要导入模块: from lockfile import LockFile [as 别名]
# 或者: from lockfile.LockFile import release [as 别名]
def write_relay_log(relayNumber, relaySeconds):
    config = ConfigParser.RawConfigParser()

    if not os.path.exists(lock_directory):
        os.makedirs(lock_directory)
    if not Terminate:
        lock = LockFile(relay_lock_path)
        while not lock.i_am_locking():
            try:
                logging.info("[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.info("[Write Relay Log] Gained lock: %s", lock.path)
        relay = [0] * 9
        for n in range(1, 9):
            if n == relayNumber:
                relay[relayNumber] = relaySeconds
        try:
            with open(relay_log_file_tmp, "ab") as relaylog:
                relaylog.write('{0} {1} {2} {3} {4} {5} {6} {7} {8}\n'.format(
                    datetime.datetime.now().strftime("%Y %m %d %H %M %S"), 
                    relay[1], relay[2], relay[3], relay[4],
                    relay[5], relay[6], relay[7], relay[8]))
        except:
            logging.warning("[Write Relay Log] Unable to append data to %s", relay_log_file_tmp)
        logging.info("[Write Relay Log] Removing lock: %s", lock.path)
        lock.release()
开发者ID:toddkaufmann,项目名称:Automated-Mushroom-Cultivator,代码行数:32,代码来源:mycodo.py

示例14: release

# 需要导入模块: from lockfile import LockFile [as 别名]
# 或者: from lockfile.LockFile import release [as 别名]
 def release(self):
     """
     Method used to release a lock using the lockfile module.
     """
     lock = LockFile(self.lockfile)
     if lock.i_am_locking():
         lock.release()
开发者ID:misterte,项目名称:django-cacheq,代码行数:9,代码来源:utils.py

示例15: addScanResult

# 需要导入模块: from lockfile import LockFile [as 别名]
# 或者: from lockfile.LockFile import release [as 别名]
        def addScanResult( self,\
                           scanResult,\
                           ADD_MODE = NEW_SCAN_RESULT ):
                
                lock = LockFile(self.m_TokenFileName)

		#ОБРАБОТКА НЕВОЗМОЖНОСТИ ДОЖДАТЬСЯ РАЗБЛОКИРОВАНИЯ ФАЙЛА
                lock.acquire( SECONDS_WAIT_FOR_UNLOCK )

                f = open(self.m_TokenFileName,\
                         'r+')
                listScanResult = self.loadScanResults( f )

                idToken = 0
                
                if ( ADD_MODE == TO_EXIST_SCAN_RESULT ):
                        listScanResult.setScanResultByIdToken( scanResult )
                else:
                        idToken = listScanResult.addScanResult( scanResult )

                f.seek(0)
                f.write( listScanResult.toJSON() )
                f.close()
                lock.release()

                return idToken
开发者ID:Rentert,项目名称:form_of_voting,代码行数:28,代码来源:TokenFileWorker.py


注:本文中的lockfile.LockFile.release方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。