本文整理汇总了Python中fcntl.LOCK_NB属性的典型用法代码示例。如果您正苦于以下问题:Python fcntl.LOCK_NB属性的具体用法?Python fcntl.LOCK_NB怎么用?Python fcntl.LOCK_NB使用的例子?那么, 这里精选的属性代码示例或许可以为您提供帮助。您也可以进一步了解该属性所在类fcntl
的用法示例。
在下文中一共展示了fcntl.LOCK_NB属性的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: load
# 需要导入模块: import fcntl [as 别名]
# 或者: from fcntl import LOCK_NB [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
示例2: containers
# 需要导入模块: import fcntl [as 别名]
# 或者: from fcntl import LOCK_NB [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
示例3: __init__
# 需要导入模块: import fcntl [as 别名]
# 或者: from fcntl import LOCK_NB [as 别名]
def __init__(self, path, flags, seconds=default_timeout):
"""Construct a lockable file handle. Handles are recycled.
If seconds is 0, LOCK_NB will be set. If LOCK_NB is set, seconds will
be set to 0. If seconds is None, there will be no timeout; but flags
will not be adjusted in any way.
"""
full = os.path.abspath(path)
flags, seconds = nb_seconds(flags, seconds)
if full not in locks:
_Struct.__init__(self, path=full,
handle=None,
fd=None,
flags=flags,
seconds=seconds)
locks[self.path] = self
示例4: lock
# 需要导入模块: import fcntl [as 别名]
# 或者: from fcntl import LOCK_NB [as 别名]
def lock(self):
if self.handle is None or self.handle.closed:
self.handle = open(self.path, "w+")
self.fd = self.handle.fileno()
if (self.flags & fcntl.LOCK_NB) != 0 or self.seconds is None:
try:
fcntl.flock(self.handle, self.flags)
except IOError as e:
if e.errno not in [errno.EACCES, errno.EAGAIN]:
raise e
raise Locked(self.path)
else:
with timeout(self.seconds):
try:
fcntl.flock(self.handle, self.flags)
except IOError as e:
errnos = [errno.EINTR, errno.EACCES, errno.EAGAIN]
if e.errno not in errnos:
raise e
raise Timeout(self.path)
示例5: udpate_status
# 需要导入模块: import fcntl [as 别名]
# 或者: from fcntl import LOCK_NB [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()
示例6: _create_pid_file
# 需要导入模块: import fcntl [as 别名]
# 或者: from fcntl import LOCK_NB [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.")
示例7: __enter__
# 需要导入模块: import fcntl [as 别名]
# 或者: from fcntl import LOCK_NB [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
示例8: write_pidfile
# 需要导入模块: import fcntl [as 别名]
# 或者: from fcntl import LOCK_NB [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)
示例9: acquire
# 需要导入模块: import fcntl [as 别名]
# 或者: from fcntl import LOCK_NB [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))
示例10: AcquireFileLock
# 需要导入模块: import fcntl [as 别名]
# 或者: from fcntl import LOCK_NB [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)
示例11: bounce_lock
# 需要导入模块: import fcntl [as 别名]
# 或者: from fcntl import LOCK_NB [as 别名]
def bounce_lock(name):
"""Acquire a bounce lockfile for the name given. The name should generally
be the service namespace being bounced.
This is a contextmanager. Please use it via 'with bounce_lock(name):'.
:param name: The lock name to acquire"""
lockfile = "/var/lock/%s.lock" % name
with open(lockfile, "w") as fd:
remove = False
try:
fcntl.lockf(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
remove = True
yield
except IOError:
raise LockHeldException("Service %s is already being bounced!" % name)
finally:
if remove:
os.remove(lockfile)
示例12: test_bounce_lock
# 需要导入模块: import fcntl [as 别名]
# 或者: from fcntl import LOCK_NB [as 别名]
def test_bounce_lock(self):
import fcntl
lock_name = "the_internet"
lock_file = "/var/lock/%s.lock" % lock_name
fake_fd = mock.mock_open()
with mock.patch("builtins.open", fake_fd, autospec=None) as open_patch:
with mock.patch("fcntl.lockf", autospec=None) as lockf_patch:
with mock.patch("os.remove", autospec=None) as remove_patch:
with bounce_lib.bounce_lock(lock_name):
pass
open_patch.assert_called_once_with(lock_file, "w")
lockf_patch.assert_called_once_with(
fake_fd.return_value, fcntl.LOCK_EX | fcntl.LOCK_NB
)
fake_fd.return_value.__exit__.assert_called_once_with(None, None, None)
remove_patch.assert_called_once_with(lock_file)
示例13: lock
# 需要导入模块: import fcntl [as 别名]
# 或者: from fcntl import LOCK_NB [as 别名]
def lock(self):
"""
Locks the package to avoid concurrent operations on its shared
resources.
Currently, the only resource shared among scripts executed from
different directories is the repository.
"""
if not self.locking_enabled:
LOG.debug("This package has no shared resources to lock")
return
LOG.debug("Checking for lock on file {}.".format(self.lock_file_path))
self.lock_file = open(self.lock_file_path, "w")
try:
fcntl.lockf(self.lock_file, fcntl.LOCK_EX | fcntl.LOCK_NB)
except IOError as exc:
RESOURCE_UNAVAILABLE_ERROR = 11
if exc.errno == RESOURCE_UNAVAILABLE_ERROR:
LOG.info("Waiting for other process to finish operations "
"on {}.".format(self.name))
else:
raise
fcntl.lockf(self.lock_file, fcntl.LOCK_EX)
示例14: write_pid
# 需要导入模块: import fcntl [as 别名]
# 或者: from fcntl import LOCK_NB [as 别名]
def write_pid(path):
"""Writes our PID to *path*."""
try:
pid = os.getpid()
with io.open(path, mode='w', encoding='utf-8') as pidfile:
# Get a non-blocking exclusive lock
fcntl.flock(pidfile.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
pidfile.seek(0)
pidfile.truncate(0)
pidfile.write(unicode(pid))
except:
logging.error(_("Could not write PID file: %s") % path)
raise # This raises the original exception
finally:
try:
pidfile.close()
except:
pass
示例15: singleton
# 需要导入模块: import fcntl [as 别名]
# 或者: from fcntl import LOCK_NB [as 别名]
def singleton(lockfile, text="semaphore"):
"""
Open a lockfile exclusively.
"""
if not lockfile.parent.exists():
mkdir(lockfile.parent)
try:
if has_fcntl:
f = open(lockfile, "w")
fcntl.lockf(f, fcntl.LOCK_EX | fcntl.LOCK_NB)
else:
if lockfile.exists():
lockfile.unlink()
fd = os.open(lockfile, os.O_CREAT | os.O_EXCL | os.O_RDWR)
f = open(fd, "w")
f.write(text)
except IOError:
return None
return f