當前位置: 首頁>>代碼示例>>Python>>正文


Python fcntl.LOCK_EX屬性代碼示例

本文整理匯總了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) 
開發者ID:dumingyou,項目名稱:mysql_repl_repair,代碼行數:21,代碼來源:mysql_repl_repair2.py

示例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 
開發者ID:dumingyou,項目名稱:mysql_repl_repair,代碼行數:23,代碼來源:mysql_repl_repair.py

示例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 
開發者ID:google,項目名稱:gtest-parallel,代碼行數:22,代碼來源:gtest_parallel.py

示例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 
開發者ID:EDCD,項目名稱:EDMarketConnector,代碼行數:24,代碼來源:eddn.py

示例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 
開發者ID:mesosphere-backup,項目名稱:deimos,代碼行數:21,代碼來源:docker.py

示例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 
開發者ID:mesosphere-backup,項目名稱:deimos,代碼行數:18,代碼來源:state.py

示例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() 
開發者ID:BishopFox,項目名稱:IDontSpeakSSL,代碼行數:18,代碼來源:utils.py

示例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.") 
開發者ID:qunarcorp,項目名稱:open_dnsdb,代碼行數:18,代碼來源:updater.py

示例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 
開發者ID:perfsonar,項目名稱:pscheduler,代碼行數:18,代碼來源:pidfile.py

示例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) 
開發者ID:smarthomeNG,項目名稱:smarthome,代碼行數:23,代碼來源:daemon.py

示例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)) 
開發者ID:Tufin,項目名稱:pytos,代碼行數:21,代碼來源:utils.py

示例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) 
開發者ID:FSecureLABS,項目名稱:Jandroid,代碼行數:18,代碼來源:lock.py

示例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) 
開發者ID:sippy,項目名稱:rtp_cluster,代碼行數:17,代碼來源:SipLogger.py

示例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) 
開發者ID:gilesknap,項目名稱:gphotos-sync,代碼行數:43,代碼來源:Main.py

示例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) 
開發者ID:dlenski,項目名稱:vpn-slice,代碼行數:14,代碼來源:posix.py


注:本文中的fcntl.LOCK_EX屬性示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。