本文整理匯總了Python中fcntl.LOCK_EX屬性的典型用法代碼示例。如果您正苦於以下問題:Python fcntl.LOCK_EX屬性的具體用法?Python fcntl.LOCK_EX怎麽用?Python fcntl.LOCK_EX使用的例子?那麽, 這裏精選的屬性代碼示例或許可以為您提供幫助。您也可以進一步了解該屬性所在類fcntl
的用法示例。
在下文中一共展示了fcntl.LOCK_EX屬性的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: run
# 需要導入模塊: import fcntl [as 別名]
# 或者: from fcntl import LOCK_EX [as 別名]
def run(self):
"check mysql replication and handle errors"
global sigint_up
# add file lock first to sure only 1 process is running on this instance
if not os.path.exists(self.lockfile):
os.system("touch %s" %(self.lockfile))
f = open(self.lockfile, "r")
try:
fcntl.flock(f.fileno(), fcntl.LOCK_EX|fcntl.LOCK_NB)
self.logger.debug("get file lock on %s success" %(self.lockfile))
except Exception, e:
msg = "can't get lock for mysql %s, please check script is already running" %(self.port)
self.logger.error(msg)
sigint_up = True
raise Exception(msg)
示例2: run
# 需要導入模塊: import fcntl [as 別名]
# 或者: from fcntl import LOCK_EX [as 別名]
def run(self):
"check mysql replication and handle errors"
global sigint_up
# add file lock first to sure only 1 process is running on this instance
if not os.path.exists(self.lockfile):
os.system("touch %s" %(self.lockfile))
f = open(self.lockfile, "r")
try:
fcntl.flock(f.fileno(), fcntl.LOCK_EX|fcntl.LOCK_NB)
self.logger.debug("get file lock on %s success" %(self.lockfile))
except Exception, e:
msg = "can't get lock for mysql %s, please check script is already running" %(self.port)
self.logger.error(msg)
sigint_up = True
raise Exception(msg)
# check binlog format
示例3: __enter__
# 需要導入模塊: import fcntl [as 別名]
# 或者: from fcntl import LOCK_EX [as 別名]
def __enter__(self):
self._fo = open(self._filename, self._mode)
# Regardless of opening mode we always seek to the beginning of file.
# This simplifies code working with LockedFile and also ensures that
# we lock (and unlock below) always the same region in file on win32.
self._fo.seek(0)
try:
if sys.platform == 'win32':
# We are locking here fixed location in file to use it as
# an exclusive lock on entire file.
msvcrt.locking(self._fo.fileno(), msvcrt.LK_LOCK, 1)
else:
fcntl.flock(self._fo.fileno(), fcntl.LOCK_EX)
except IOError:
self._fo.close()
raise
return self._fo
示例4: load
# 需要導入模塊: import fcntl [as 別名]
# 或者: from fcntl import LOCK_EX [as 別名]
def load(self):
# Try to obtain exclusive access to the journal cache
filename = join(config.app_dir, 'replay.jsonl')
try:
try:
# Try to open existing file
self.replayfile = open(filename, 'r+', buffering=1)
except:
if exists(filename):
raise # Couldn't open existing file
else:
self.replayfile = open(filename, 'w+', buffering=1) # Create file
if sys.platform != 'win32': # open for writing is automatically exclusive on Windows
lockf(self.replayfile, LOCK_EX|LOCK_NB)
except:
if __debug__: print_exc()
if self.replayfile:
self.replayfile.close()
self.replayfile = None
return False
self.replaylog = [line.strip() for line in self.replayfile]
return True
示例5: containers
# 需要導入模塊: import fcntl [as 別名]
# 或者: from fcntl import LOCK_EX [as 別名]
def containers(self, *args):
log.info(" ".join(args))
data = Run(data=True)(deimos.docker.docker("ps", "--no-trunc", "-q"))
mesos_ids = []
for line in data.splitlines():
cid = line.strip()
state = deimos.state.State(self.state_root, docker_id=cid)
if not state.exists():
continue
try:
state.lock("wait", LOCK_SH | LOCK_NB)
except deimos.flock.Err: # LOCK_EX held, so launch() is running
mesos_ids += [state.mesos_container_id()]
containers = Containers()
for mesos_id in mesos_ids:
container = containers.containers.add()
container.value = mesos_id
recordio.writeProto(containers)
return 0
示例6: lock
# 需要導入模塊: import fcntl [as 別名]
# 或者: from fcntl import LOCK_EX [as 別名]
def lock(self, name, flags, seconds=60):
fmt_time = "indefinite" if seconds is None else "%ds" % seconds
fmt_flags = deimos.flock.format_lock_flags(flags)
flags, seconds = deimos.flock.nb_seconds(flags, seconds)
log.info("request // %s %s (%s)", name, fmt_flags, fmt_time)
p = self.resolve(os.path.join("lock", name), mkdir=True)
lk = deimos.flock.LK(p, flags, seconds)
try:
lk.lock()
except deimos.flock.Err:
log.error("failure // %s %s (%s)", name, fmt_flags, fmt_time)
raise
if (flags & LOCK_EX) != 0:
lk.handle.write(iso() + "\n")
log.info("success // %s %s (%s)", name, fmt_flags, fmt_time)
return lk
示例7: udpate_status
# 需要導入模塊: import fcntl [as 別名]
# 或者: from fcntl import LOCK_EX [as 別名]
def udpate_status(status_file_path, module_data, module):
lock_file_path = "{}.lock".format(status_file_path)
while True:
status_file_lock = open(lock_file_path, 'r')
try:
fcntl.flock(status_file_lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
with open(status_file_path, "r+") as status_file:
data = json.load(status_file)
status_file.seek(0)
data[module].update(module_data)
json.dump(data, status_file)
fcntl.flock(status_file_lock, fcntl.LOCK_UN)
return
except:
time.sleep(0.1)
status_file_lock.close()
示例8: _create_pid_file
# 需要導入模塊: import fcntl [as 別名]
# 或者: from fcntl import LOCK_EX [as 別名]
def _create_pid_file():
global fp
pidfile = CONF.etc.pidfile
if pidfile is None:
raise UpdaterErr("No pidfile option found in config file.")
try:
fp = open(pidfile, 'w')
# LOCK_EX /* exclusive lock */
# LOCK_NB * don't block when locking */
fcntl.flock(fp, fcntl.LOCK_EX | fcntl.LOCK_NB)
fp.truncate()
pid = os.getpid()
fp.write(str(pid))
fp.flush()
except Exception as e:
raise UpdaterErr("Failed to lock pidfile, perhaps named_updater is already running.")
示例9: __enter__
# 需要導入模塊: import fcntl [as 別名]
# 或者: from fcntl import LOCK_EX [as 別名]
def __enter__(self):
if self.path is None:
return self.pidfile
self.pidfile = open(self.path, "a+")
try:
fcntl.flock(self.pidfile.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
except IOError:
self.pidfile = None
raise SystemExit("Already running according to " + self.path)
self.pidfile.seek(0)
self.pidfile.truncate()
self.pidfile.write(str(os.getpid()))
self.pidfile.flush()
self.pidfile.seek(0)
return self.pidfile
示例10: write_pidfile
# 需要導入模塊: import fcntl [as 別名]
# 或者: from fcntl import LOCK_EX [as 別名]
def write_pidfile(pid, pidfile):
"""
This method writes the PID to the pidfile and locks it while the process is running.
:param pid: PID of SmartHomeNG
:param pidfile: Name of the pidfile to write to
:type pid: int
:type pidfile: str
"""
fd = open(pidfile, 'w+')
fd.write("%s" % pid)
fd.close()
# lock pidfile:
try:
fd = os.open(pidfile, os.O_RDONLY)
fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
# don't close fd or lock is gone
except OSError as e:
print("Could not lock pid file: %d (%s)" % (e.errno, e.strerror) , file=sys.stderr)
示例11: acquire
# 需要導入模塊: import fcntl [as 別名]
# 或者: from fcntl import LOCK_EX [as 別名]
def acquire(self, blocking=None):
# Give an opportunity to set blocking with the class for context use
if blocking is None:
blocking = self.blocking
if blocking:
lock_mode = fcntl.LOCK_EX
else:
lock_mode = fcntl.LOCK_EX | fcntl.LOCK_NB
if self.lock_file.closed:
self._get_lock_file_handle()
if not self.locked:
try:
self.lock = fcntl.flock(self.lock_file, lock_mode)
self.locked = True
except IOError:
raise IOError("File '{}' is already locked.".format(self.lock_file_name))
else:
raise IOError("File '{}' is already locked.".format(self.lock_file_name))
示例12: AcquireFileLock
# 需要導入模塊: import fcntl [as 別名]
# 或者: from fcntl import LOCK_EX [as 別名]
def AcquireFileLock(target_file, flags):
""" Lock the target file. Note that if |target_file| is closed, the lock is
automatically released.
Args:
target_file: file handle of the file to acquire lock.
flags: can be any of the type LOCK_EX, LOCK_SH, LOCK_NB, or a bitwise
OR combination of flags.
"""
assert flags in (
LOCK_EX, LOCK_SH, LOCK_NB, LOCK_EX | LOCK_NB, LOCK_SH | LOCK_NB)
if os.name == 'nt':
_LockImplWin(target_file, flags)
elif os.name == 'posix':
_LockImplPosix(target_file, flags)
else:
raise NotImplementedError('%s is not supported' % os.name)
示例13: do_write
# 需要導入模塊: import fcntl [as 別名]
# 或者: from fcntl import LOCK_EX [as 別名]
def do_write(self, obuf):
my_flock = flock
try:
my_flock(self.log, LOCK_EX)
except IOError as e:
# Catch ENOTSUP
if e.args[0] != 45:
raise e
my_flock = lambda x, y: None
try:
self.log.write(obuf)
self.log.flush()
except:
pass
my_flock(self.log, LOCK_UN)
示例14: main
# 需要導入模塊: import fcntl [as 別名]
# 或者: from fcntl import LOCK_EX [as 別名]
def main(self, test_args: dict = None):
start_time = datetime.now()
args = self.parser.parse_args(test_args)
root_folder = Path(args.root_folder).absolute()
db_path = Path(args.db_path) if args.db_path else root_folder
if not root_folder.exists():
root_folder.mkdir(parents=True, mode=0o700)
setup_logging(args.log_level, args.logfile, root_folder)
log.warning(f"gphotos-sync {__version__} {start_time}")
args = self.fs_checks(root_folder, args)
lock_file = db_path / "gphotos.lock"
fp = lock_file.open("w")
with fp:
try:
if os.name != "nt":
fcntl.lockf(fp, fcntl.LOCK_EX | fcntl.LOCK_NB)
except IOError:
log.warning("EXITING: database is locked")
sys.exit(0)
log.info(self.version_string)
# configure and launch
# noinspection PyBroadException
try:
self.setup(args, db_path)
self.start(args)
except KeyboardInterrupt:
log.error("User cancelled download")
log.debug("Traceback", exc_info=True)
except BaseException:
log.error("\nProcess failed.", exc_info=True)
finally:
log.warning("Done.")
elapsed_time = datetime.now() - start_time
log.info("Elapsed time = %s", elapsed_time)
示例15: write_hosts
# 需要導入模塊: import fcntl [as 別名]
# 或者: from fcntl import LOCK_EX [as 別名]
def write_hosts(self, host_map, name):
tag = 'vpn-slice-{} AUTOCREATED'.format(name)
with open(self.path, 'r+') as hostf:
fcntl.flock(hostf, fcntl.LOCK_EX) # POSIX only, obviously
lines = hostf.readlines()
keeplines = [l for l in lines if not l.endswith('# %s\n' % tag)]
hostf.seek(0, 0)
hostf.writelines(keeplines)
for ip, names in host_map:
print('%s %s\t\t# %s' % (ip, ' '.join(names), tag), file=hostf)
hostf.truncate()
return len(host_map) or len(lines) - len(keeplines)