本文整理汇总了Python中lockfile.LockFile.i_am_locking方法的典型用法代码示例。如果您正苦于以下问题:Python LockFile.i_am_locking方法的具体用法?Python LockFile.i_am_locking怎么用?Python LockFile.i_am_locking使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类lockfile.LockFile
的用法示例。
在下文中一共展示了LockFile.i_am_locking方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: main
# 需要导入模块: from lockfile import LockFile [as 别名]
# 或者: from lockfile.LockFile import i_am_locking [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()
示例2: write_relay_log
# 需要导入模块: from lockfile import LockFile [as 别名]
# 或者: from lockfile.LockFile import i_am_locking [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()
示例3: run
# 需要导入模块: from lockfile import LockFile [as 别名]
# 或者: from lockfile.LockFile import i_am_locking [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
示例4: run
# 需要导入模块: from lockfile import LockFile [as 别名]
# 或者: from lockfile.LockFile import i_am_locking [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
示例5: run
# 需要导入模块: from lockfile import LockFile [as 别名]
# 或者: from lockfile.LockFile import i_am_locking [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
示例6: main
# 需要导入模块: from lockfile import LockFile [as 别名]
# 或者: from lockfile.LockFile import i_am_locking [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()
示例7: write_relay_log
# 需要导入模块: from lockfile import LockFile [as 别名]
# 或者: from lockfile.LockFile import i_am_locking [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()
示例8: release
# 需要导入模块: from lockfile import LockFile [as 别名]
# 或者: from lockfile.LockFile import i_am_locking [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()
示例9: write_ht_sensor_log
# 需要导入模块: from lockfile import LockFile [as 别名]
# 或者: from lockfile.LockFile import i_am_locking [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()
示例10: run
# 需要导入模块: from lockfile import LockFile [as 别名]
# 或者: from lockfile.LockFile import i_am_locking [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()
示例11: write_sensor_log
# 需要导入模块: from lockfile import LockFile [as 别名]
# 或者: from lockfile.LockFile import i_am_locking [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()
示例12: run
# 需要导入模块: from lockfile import LockFile [as 别名]
# 或者: from lockfile.LockFile import i_am_locking [as 别名]
def run(self):
cmdline = sys.argv[1:] # Grab args from cmdline
# If we are running in an openshift pod (via `oc new-app`) then
# there is no cmdline but we want to default to "atomicapp run".
# In this case copy files to cwd and use the working directory.
if Utils.running_on_openshift():
cmdline = 'run -v --dest=none /{}'.format(APP_ENT_PATH).split()
# We want to be able to place options anywhere on the command
# line. We have added all global options to each subparser,
# but subparsers require all options to be after the 'action'
# keyword. In order to handle this we just need to figure out
# what subparser will be used and move it's keyword to the front
# of the line.
# NOTE: Also allow "mode" to override 'action' if specified
args, _ = self.parser.parse_known_args(cmdline)
cmdline.remove(args.action) # Remove 'action' from the cmdline
if args.mode:
args.action = args.mode # Allow mode to override 'action'
cmdline.insert(0, args.action) # Place 'action' at front
logger.info("Action/Mode Selected is: %s" % args.action)
# Finally, parse args and give error if necessary
args = self.parser.parse_args(cmdline)
# Set logging level
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()
示例13: main
# 需要导入模块: from lockfile import LockFile [as 别名]
# 或者: from lockfile.LockFile import i_am_locking [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()
示例14: Lock
# 需要导入模块: from lockfile import LockFile [as 别名]
# 或者: from lockfile.LockFile import i_am_locking [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)
示例15: append_line_to_mycodo_log
# 需要导入模块: from lockfile import LockFile [as 别名]
# 或者: from lockfile.LockFile import i_am_locking [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()