本文整理汇总了Python中lockfile.LockFile.break_lock方法的典型用法代码示例。如果您正苦于以下问题:Python LockFile.break_lock方法的具体用法?Python LockFile.break_lock怎么用?Python LockFile.break_lock使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类lockfile.LockFile
的用法示例。
在下文中一共展示了LockFile.break_lock方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: main
# 需要导入模块: from lockfile import LockFile [as 别名]
# 或者: from lockfile.LockFile import break_lock [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()
示例2: write_relay_log
# 需要导入模块: from lockfile import LockFile [as 别名]
# 或者: from lockfile.LockFile import break_lock [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()
示例3: write_sensor_log
# 需要导入模块: from lockfile import LockFile [as 别名]
# 或者: from lockfile.LockFile import break_lock [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()
示例4: write_ht_sensor_log
# 需要导入模块: from lockfile import LockFile [as 别名]
# 或者: from lockfile.LockFile import break_lock [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()
示例5: write_relay_log
# 需要导入模块: from lockfile import LockFile [as 别名]
# 或者: from lockfile.LockFile import break_lock [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()
示例6: main
# 需要导入模块: from lockfile import LockFile [as 别名]
# 或者: from lockfile.LockFile import break_lock [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
from .connectivity import check_internet_connection
from .update_checker import check_for_updates
lock = LockFile('/tmp/spoppy')
try:
try:
# Try for 1s to acquire the lock
lock.acquire(1)
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
)
click.echo(
'You can try removing the lock file by responding [rm]. '
'spoppy will exit on all other inputs'
)
try:
response = raw_input('')
except NameError:
response = input('')
if response == 'rm':
lock.break_lock()
else:
raise TypeError('Could not get lock')
except TypeError:
pass
else:
check_internet_connection()
# Check for updates
check_for_updates(click, get_version(), lock)
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()
示例7: State
# 需要导入模块: from lockfile import LockFile [as 别名]
# 或者: from lockfile.LockFile import break_lock [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 break_lock [as 别名]
class Lock():
"""Simple implementation of a mutex lock using the file systems. Works on
*nix systems."""
path = None
lock = None
def __init__(self, path):
try:
from lockfile import LockFile
except ImportError:
from lockfile import FileLock
# Different naming in older versions of lockfile
LockFile = FileLock
self.path = path
self.lock = LockFile(path)
def obtain(self):
import os
import logging
from lockfile import AlreadyLocked
logger = logging.getLogger()
try:
self.lock.acquire(0)
logger.debug("Successfully obtained lock: %s" % self.path)
except AlreadyLocked:
return False
return True
def release(self):
import os
import logging
logger = logging.getLogger()
if not self.has_lock():
raise Exception("Unable to release lock that is owned by another process")
self.lock.release()
logger.debug("Successfully released lock: %s" % self.path)
def has_lock(self):
return self.lock.i_am_locking()
def clear(self):
import os
import logging
logger = logging.getLogger()
self.lock.break_lock()
logger.debug("Successfully cleared lock: %s" % self.path)
示例9: append_line_to_mycodo_log
# 需要导入模块: from lockfile import LockFile [as 别名]
# 或者: from lockfile.LockFile import break_lock [as 别名]
def append_line_to_mycodo_log(log_file_path, log_lock_path, log_line):
"""
Appends given line to log file.
:return:
:rtype:
:param log_file_path: Path to the Log File
:type log_file_path: str
:param log_lock_path: Path to the Lock File
:type log_lock_path: str
:param log_line: String to write to the Log File
:type log_line: str
"""
lock = LockFile(log_lock_path)
while not lock.i_am_locking():
try:
logging.debug("[Write Sensor Log] Acquiring Lock: {}".format(lock.path))
lock.acquire(timeout=60) # wait up to 60 seconds
except: # TODO Needs better catch statement
logging.warning("[Write Sensor Log] Breaking Lock to Acquire: {}".format(lock.path))
lock.break_lock()
lock.acquire()
finally:
logging.debug("[Write Sensor Log] Gained lock: {}".format(lock.path))
try:
with open(log_file_path, "ab") as sensorlog:
pass
sensorlog.write(log_line + "\n")
# Temperature:
# sensorlog.write('{"%Y/%m/%d-%H:%M:%S"} {:.1f} {}'.format(now(), sensor_t_read_temp_c[sensor], sensor))
# Temperature/Humidity:
# sensorlog.write('{"%Y/%m/%d-%H:%M:%S"} {:.1f} {:.1f} {:.1f} {}'.format(now(), sensor_ht_read_temp_c[sensor], sensor_ht_read_hum[sensor], sensor_ht_dewpt_c[sensor], sensor))
# CO2
# sensorlog.write('{"%Y/%m/%d-%H:%M:%S"} {} {}'.format(now(), sensor_co2_read_co2[sensor], sensor))
# Pressure
# sensorlog.write('{"%Y/%m/%d-%H:%M:%S"} {:.1f} {} {:.1f} {}'.format(now(), sensor_press_read_temp_c[sensor], sensor_press_read_press[sensor], sensor_press_read_alt[sensor], sensor))
# Relay
# relaylog.write('{"%Y/%m/%d-%H:%M:%S"} {} {} {} {:.2f}'.format(now(), sensor, relayNumber, gpio, relaySeconds))
logging.debug("[Write Sensor Log] Data appended to {}".format(
log_file_path))
except: # TODO Needs better catch statement
logging.warning("[Write Sensor Log] Unable to append data to %s",
log_file_path)
logging.debug("[Write Sensor Log] Removing lock: {}".format(lock.path))
lock.release()
示例10: do_lock
# 需要导入模块: from lockfile import LockFile [as 别名]
# 或者: from lockfile.LockFile import break_lock [as 别名]
def do_lock(*args, **kwargs):
lock = LockFile(path)
while not lock.i_am_locking():
try:
lock.acquire(timeout=5)
except LockTimeout:
lock.break_lock()
try:
rv = f(*args, **kwargs)
finally:
lock.release()
return rv
示例11: MailQueue
# 需要导入模块: from lockfile import LockFile [as 别名]
# 或者: from lockfile.LockFile import break_lock [as 别名]
class MailQueue(object):
QUEUE_FILE = '/tmp/mail.queue'
MAX_ATTEMPTS = 3
def __init__(self):
self.queue = None
def append(self, message):
self.queue.append(QueueItem(message))
@classmethod
def is_empty(cls):
if not os.path.exists(cls.QUEUE_FILE):
return True
try:
return os.stat(cls.QUEUE_FILE).st_size == 0
except OSError:
return True
def _get_queue(self):
try:
with open(self.QUEUE_FILE, 'rb') as f:
self.queue = pickle.loads(f.read())
except (pickle.PickleError, EOFError):
self.queue = []
def __enter__(self):
self._lock = LockFile(self.QUEUE_FILE)
while not self._lock.i_am_locking():
try:
self._lock.acquire(timeout=330)
except LockTimeout:
self._lock.break_lock()
if not os.path.exists(self.QUEUE_FILE):
open(self.QUEUE_FILE, 'a').close()
self._get_queue()
return self
def __exit__(self, typ, value, traceback):
with open(self.QUEUE_FILE, 'wb+') as f:
if self.queue:
f.write(pickle.dumps(self.queue))
self._lock.release()
if typ is not None:
raise
示例12: sync
# 需要导入模块: from lockfile import LockFile [as 别名]
# 或者: from lockfile.LockFile import break_lock [as 别名]
def sync(labels):
"""
Attempts to run several methods Certificate discovery. This is
run on a periodic basis and updates the Lemur datastore with the
information it discovers.
"""
if not labels:
sys.stdout.write("Active\tLabel\tDescription\n")
for source in source_service.get_all():
sys.stdout.write(
"{active}\t{label}\t{description}!\n".format(
label=source.label,
description=source.description,
active=source.active
)
)
else:
start_time = time.time()
lock_file = "/tmp/.lemur_lock"
sync_lock = LockFile(lock_file)
while not sync_lock.i_am_locking():
try:
sync_lock.acquire(timeout=10) # wait up to 10 seconds
sys.stdout.write("[+] Staring to sync sources: {labels}!\n".format(labels=labels))
labels = labels.split(",")
if labels[0] == 'all':
source_sync()
else:
source_sync(labels=labels)
sys.stdout.write(
"[+] Finished syncing sources. Run Time: {time}\n".format(
time=(time.time() - start_time)
)
)
except LockTimeout:
sys.stderr.write(
"[!] Unable to acquire file lock on {file}, is there another sync running?\n".format(
file=lock_file
)
)
sync_lock.break_lock()
sync_lock.acquire()
sync_lock.release()
sync_lock.release()
示例13: MCP342x_read
# 需要导入模块: from lockfile import LockFile [as 别名]
# 或者: from lockfile.LockFile import break_lock [as 别名]
class MCP342x_read(object):
def __init__(self, logger, address, channel, resolution):
self.logger = logger
self.i2c_address = address
self.channel = channel
self.resolution = resolution
if GPIO.RPI_INFO['P1_REVISION'] in [2, 3]:
self.I2C_bus_number = 1
else:
self.I2C_bus_number = 0
self.bus = smbus.SMBus(self.I2C_bus_number)
self.lock_file = "/var/lock/mycodo_adc_0x{:02X}.pid".format(self.i2c_address)
def setup_lock(self):
self.execution_timer = timeit.default_timer()
try:
self.lock = LockFile(self.lock_file)
while not self.lock.i_am_locking():
try:
self.logger.debug("[Analog->Digital Converter 0x{:02X}] Acquiring Lock: {}".format(self.i2c_address, self.lock.path))
self.lock.acquire(timeout=60) # wait up to 60 seconds
except:
self.logger.warning("[Analog->Digital Converter 0x{:02X}] Waited 60 seconds. Breaking lock to acquire {}".format(self.i2c_address, self.lock.path))
self.lock.break_lock()
self.lock.acquire()
self.logger.debug("[Analog->Digital Converter 0x{:02X}] Acquired Lock: {}".format(self.i2c_address, self.lock.path))
self.logger.debug("[Analog->Digital Converter 0x{:02X}] Executed in {}ms".format(self.i2c_address, (timeit.default_timer()-self.execution_timer)*1000))
return 1, "Success"
except Exception as msg:
return 0, "Analog->Digital Converter Fail: {}".format(msg)
def release_lock(self):
self.lock.release()
def read(self):
try:
time.sleep(0.1)
self.setup_lock()
adc = MCP342x(self.bus, self.i2c_address, channel=self.channel-1, resolution=self.resolution)
response = adc.convert_and_read()
self.release_lock()
return 1, response
except Exception as msg:
self.release_lock()
return 0, "Fail: {}".format(msg)
示例14: read
# 需要导入模块: from lockfile import LockFile [as 别名]
# 或者: from lockfile.LockFile import break_lock [as 别名]
def read(self):
lock = LockFile(K30_LOCK_FILE)
try:
# Acquire lock on K30 to ensure more than one read isn't
# being attempted at once.
while not lock.i_am_locking():
try:
lock.acquire(timeout=60) # wait up to 60 seconds before breaking lock
except:
lock.break_lock()
lock.acquire()
self._co2 = self.get_measurement()
lock.release()
except:
lock.release()
return 1
示例15: State
# 需要导入模块: from lockfile import LockFile [as 别名]
# 或者: from lockfile.LockFile import break_lock [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()