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


Python fcntl.flock方法代碼示例

本文整理匯總了Python中fcntl.flock方法的典型用法代碼示例。如果您正苦於以下問題:Python fcntl.flock方法的具體用法?Python fcntl.flock怎麽用?Python fcntl.flock使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在fcntl的用法示例。


在下文中一共展示了fcntl.flock方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: run

# 需要導入模塊: import fcntl [as 別名]
# 或者: from fcntl import flock [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 flock [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 flock [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: __exit__

# 需要導入模塊: import fcntl [as 別名]
# 或者: from fcntl import flock [as 別名]
def __exit__(self, exc_type, exc_value, traceback):
      # Flush any buffered data to disk. This is needed to prevent race
      # condition which happens from the moment of releasing file lock
      # till closing the file.
      self._fo.flush()

      try:
        if sys.platform == 'win32':
          self._fo.seek(0)
          msvcrt.locking(self._fo.fileno(), msvcrt.LK_UNLCK, 1)
        else:
          fcntl.flock(self._fo.fileno(), fcntl.LOCK_UN)
      finally:
        self._fo.close()

      return exc_value is None 
開發者ID:google,項目名稱:gtest-parallel,代碼行數:18,代碼來源:gtest_parallel.py

示例5: lock

# 需要導入模塊: import fcntl [as 別名]
# 或者: from fcntl import flock [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) 
開發者ID:mesosphere-backup,項目名稱:deimos,代碼行數:22,代碼來源:flock.py

示例6: lock_browser

# 需要導入模塊: import fcntl [as 別名]
# 或者: from fcntl import flock [as 別名]
def lock_browser(directory):
    bash = """
        set -o errexit -o nounset -o pipefail

        function files_by_inode {
          find "$1" -type f -printf '%i %p\\n' | LC_ALL=C LANG=C sort
        }

        function locking_pids_by_inode {
          cat /proc/locks |
          sed -r '
            s/^.+ ([^ ]+) +([0-9]+) [^ :]+:[^ :]+:([0-9]+) .+$/\\3 \\2 \\1/
          ' | LC_ALL=C LANG=C sort
        }

        join <(locking_pids_by_inode) <(files_by_inode "$1")
    """
    subprocess.check_call(["bash", "-c", bash, "bash",
                           os.path.abspath(directory)])

# Thanks to Glenn Maynard
# http://stackoverflow.com/questions/5255220/fcntl-flock-how-to-implement-a-timeout/5255473#5255473 
開發者ID:mesosphere-backup,項目名稱:deimos,代碼行數:24,代碼來源:flock.py

示例7: udpate_status

# 需要導入模塊: import fcntl [as 別名]
# 或者: from fcntl import flock [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 flock [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: _acquire

# 需要導入模塊: import fcntl [as 別名]
# 或者: from fcntl import flock [as 別名]
def _acquire(self, wait, wrflag, lockflag):
        wrflag |= os.O_CREAT
        fileno = os.open(self.filename, wrflag)
        try:
            if not wait:
                lockflag |= self._module.LOCK_NB
            self._module.flock(fileno, lockflag)
        except IOError:
            os.close(fileno)
            if not wait:
                # this is typically
                # "[Errno 35] Resource temporarily unavailable",
                # because of LOCK_NB
                return False
            else:
                raise
        else:
            self._filedescriptor.fileno = fileno
            return True 
開發者ID:sqlalchemy,項目名稱:dogpile.cache,代碼行數:21,代碼來源:file.py

示例10: ExecFlock

# 需要導入模塊: import fcntl [as 別名]
# 或者: from fcntl import flock [as 別名]
def ExecFlock(self, lockfile, *cmd_list):
    """
    Emulates the most basic behavior of Linux's flock(1).

    Rely on exception handling to report errors.
    Note that the stock python on SunOS has a bug where fcntl.flock(fd, LOCK_EX) always fails with EBADF,
    that's why we use this F_SETLK hack instead.
    """
    # noinspection PyUnresolvedReferences
    fd = os.open(lockfile, os.O_WRONLY|os.O_NOCTTY|os.O_CREAT, 0o666)
    if sys.platform.startswith('aix'):
      # Python on AIX is compiled with LARGEFILE support, which changes the
      # struct size.
      op = struct.pack('hhIllqq', fcntl.F_WRLCK, 0, 0, 0, 0, 0, 0)
    else:
      op = struct.pack('hhllhhl', fcntl.F_WRLCK, 0, 0, 0, 0, 0, 0)
    fcntl.fcntl(fd, fcntl.F_SETLK, op)
    return subprocess.call(cmd_list) 
開發者ID:refack,項目名稱:GYP3,代碼行數:20,代碼來源:flock_tool.py

示例11: __enter__

# 需要導入模塊: import fcntl [as 別名]
# 或者: from fcntl import flock [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

示例12: write_pidfile

# 需要導入模塊: import fcntl [as 別名]
# 或者: from fcntl import flock [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

示例13: acquire

# 需要導入模塊: import fcntl [as 別名]
# 或者: from fcntl import flock [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

示例14: __exit__

# 需要導入模塊: import fcntl [as 別名]
# 或者: from fcntl import flock [as 別名]
def __exit__(self, exc_type, exc_val, traceback):
        if (exc_type is None and self._data_written):
            os.replace(self._temp_file_path, self._config_file)
            os.chmod(self._config_file, 0o660)
            shutil.chown(self._config_file, user=USER, group=GROUP)
        else:
            self._temp_file.close()
            os.unlink(self._temp_file_path)
            if (self._Log):
                self._Log.error(f'configuration manager exiting with error: {exc_val}')

        # releasing lock for purposes specified in flock(1) man page under -u (unlock)
        fcntl.flock(self._config_lock, fcntl.LOCK_UN)
        self._config_lock.close()
        if (self._Log):
            self._Log.debug(f'file lock released for {self._file_name}')

        if (exc_type is not ValidationError):
            return True

    #will load json data from file, convert it to a python dict, then returned as object 
開發者ID:DOWRIGHTTV,項目名稱:dnxfirewall-cmd,代碼行數:23,代碼來源:dnx_file_operations.py

示例15: write_hosts

# 需要導入模塊: import fcntl [as 別名]
# 或者: from fcntl import flock [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.flock方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。