Python fcntl.flock方法代码示例

本文整理汇总了Python中fcntl.flock方法的典型用法代码示例。如果您正苦于以下问题:Python fcntl.flock方法的具体用法?Python fcntl.flock怎么用?Python fcntl.flock使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在模块fcntl的用法示例。

在下文中一共展示了fcntl.flock方法的28个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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


示例16: acquire

# 需要导入模块: import fcntl [as 别名]
# 或者: from fcntl import flock [as 别名]
def acquire(self):
        fcntl.flock(self.handle, fcntl.LOCK_EX) 
开发者ID:cea-hpc,项目名称:pcocc,代码行数:4,代码来源:Config.py


示例17: release

# 需要导入模块: import fcntl [as 别名]
# 或者: from fcntl import flock [as 别名]
def release(self):
        fcntl.flock(self.handle, fcntl.LOCK_UN) 
开发者ID:cea-hpc,项目名称:pcocc,代码行数:4,代码来源:Config.py


示例18: lock

# 需要导入模块: import fcntl [as 别名]
# 或者: from fcntl import flock [as 别名]
def lock(f, flags):
            ret = fcntl.flock(_fd(f), flags)
            return (ret == 0) 
开发者ID:lanbing510,项目名称:GTDWeb,代码行数:5,代码来源:locks.py


示例19: unlock

# 需要导入模块: import fcntl [as 别名]
# 或者: from fcntl import flock [as 别名]
def unlock(f):
            ret = fcntl.flock(_fd(f), fcntl.LOCK_UN)
            return (ret == 0) 
开发者ID:lanbing510,项目名称:GTDWeb,代码行数:5,代码来源:locks.py


示例20: _acquire

# 需要导入模块: import fcntl [as 别名]
# 或者: from fcntl import flock [as 别名]
def _acquire(self):
        open_mode = os.O_RDWR | os.O_CREAT | os.O_TRUNC
        fd = os.open(self._lock_file, open_mode)
        try:
            fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
        except (IOError, OSError):
            os.close(fd)
        else:
            self._lock_file_fd = fd
        return None 
开发者ID:a4k-openproject,项目名称:a4kScrapers,代码行数:13,代码来源:filelock.py


示例21: _release

# 需要导入模块: import fcntl [as 别名]
# 或者: from fcntl import flock [as 别名]
def _release(self):
        # Do not remove the lockfile:
        #
        #   https://github.com/benediktschmitt/py-filelock/issues/31
        #   https://stackoverflow.com/questions/17708885/flock-removing-locked-file-without-race-condition
        fd = self._lock_file_fd
        self._lock_file_fd = None
        fcntl.flock(fd, fcntl.LOCK_UN)
        os.close(fd)
        return None
# Soft lock
# ~~~~~~~~~ 
开发者ID:a4k-openproject,项目名称:a4kScrapers,代码行数:15,代码来源:filelock.py


示例22: unlock

# 需要导入模块: import fcntl [as 别名]
# 或者: from fcntl import flock [as 别名]
def unlock(self):
        if not self.handle.closed:
            fcntl.flock(self.handle, fcntl.LOCK_UN)
            self.handle.close() 
开发者ID:mesosphere-backup,项目名称:deimos,代码行数:6,代码来源:flock.py


示例23: NX_init

# 需要导入模块: import fcntl [as 别名]
# 或者: from fcntl import flock [as 别名]
def NX_init(port, baudrate):
    global ser, NX_lf, NX_reader_thread
    try:
        ser.port = port
        ser.baudrate = baudrate
        ser.timeout = 0.2
        ser.write_timeout = 1
        ser.open()
        logger.debug(_(u'Locking serial port'))
        fcntl.flock(ser.fileno(), fcntl.LOCK_EX)
        logger.debug(_(u'Clear serial buffer'))
        # Buffer des Displays leeren
        # - Ungültigen Befehl senden
        # - Aufwachbefehl senden
        ser.write('nop' + NX_lf)
        ser.write('sleep=0' + NX_lf)
        # - Warten
        ser.flush()
        time.sleep(0.2)
        # - Empfangene Zeichen löschen
        ser.flushInput()
        # Immer eine Rückmeldung erhalten
        ser.write('ref 0' + NX_lf)
        ser.flush()
    except termios.error, e:
        logger.error(_(u'termios.error in NX_init: {}').format(e[1])) 
开发者ID:WLANThermo,项目名称:WLANThermo_v2,代码行数:28,代码来源:wlt_2_nextion.py


示例24: NX_init

# 需要导入模块: import fcntl [as 别名]
# 或者: from fcntl import flock [as 别名]
def NX_init(port, baudrate):
    global ser, NX_lf
    ser.port = port
    ser.baudrate = baudrate
    ser.timeout = 0.2
    ser.open()
    import fcntl, serial
    try:
        fcntl.flock(ser.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
    except IOError:
        print ('Serial port is busy')
        return False
    # Buffer des Displays leeren
    # - Ungültigen Befehl senden
    # - Aufwachbefehl senden
    ser.write(b'nop' + NX_lf)
    ser.write(b'sleep=0' + NX_lf)
    # - Warten
    ser.flush()
    time.sleep(0.5)
    # - Empfangene Zeichen löschen
    ser.flushInput()
    # Immer eine Rückmeldung erhalten
    ser.write(b'ref 0' + NX_lf)
    ser.flush()
    return NX_waitok() 
开发者ID:WLANThermo,项目名称:WLANThermo_v2,代码行数:30,代码来源:nextion_hwclock.py


示例25: _write

# 需要导入模块: import fcntl [as 别名]
# 或者: from fcntl import flock [as 别名]
def _write(filename, contents):
        ''' Actually write the file contents to disk. This helps with mocking. '''
        tmp_filename = filename + '.yedit'
        with open(tmp_filename, 'w') as yfd:
            fcntl.flock(yfd, fcntl.LOCK_EX | fcntl.LOCK_NB)
            yfd.write(contents)
            fcntl.flock(yfd, fcntl.LOCK_UN)
        os.rename(tmp_filename, filename) 
开发者ID:RedHatOfficial,项目名称:ansible-redhat_openshift_utils,代码行数:13,代码来源:oc_obj.py


示例26: lock_file

# 需要导入模块: import fcntl [as 别名]
# 或者: from fcntl import flock [as 别名]
def lock_file(fileno: int):
    """Lock file.  Returns ``True`` if succeeded, ``False`` otherwise."""
    try:
        # Try to lock file exclusively and in non-blocking fashion
        fcntl.flock(fileno, fcntl.LOCK_EX | fcntl.LOCK_NB)
    except IOError:
        return False
    else:
        return True 
开发者ID:edgedb,项目名称:edgedb,代码行数:11,代码来源:lib.py


示例27: __init__

# 需要导入模块: import fcntl [as 别名]
# 或者: from fcntl import flock [as 别名]
def __init__(self, path):
        # Open the file and acquire a lock on the file before operating
        self.file = open(path, 'a+')
        # Get an exclusive lock (EX), non-blocking (NB)
        try:
            fcntl.flock(self.file, fcntl.LOCK_EX | fcntl.LOCK_NB)
        except OSError as exc:
            raise Exception(f"Failed to acquire exclusive lock file {path}") from exc
        # Clean lock file content
        self.file.truncate(0)
    # Return the opened file object (knowing a lock has been obtained). 
开发者ID:QwantResearch,项目名称:kartotherian_docker,代码行数:14,代码来源:lock.py


示例28: __exit__

# 需要导入模块: import fcntl [as 别名]
# 或者: from fcntl import flock [as 别名]
def __exit__(self, exc_type=None, exc_value=None, traceback=None):
        # Flush to make sure all buffered contents are written to file.
        self.file.flush()
        os.fsync(self.file.fileno())
        # Release the lock on the file.
        fcntl.flock(self.file, fcntl.LOCK_UN)
        self.file.close() 
开发者ID:QwantResearch,项目名称:kartotherian_docker,代码行数:9,代码来源:lock.py



注:本文中的fcntl.flock方法示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。