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


Python portalocker.LOCK_EX屬性代碼示例

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


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

示例1: write_file

# 需要導入模塊: import portalocker [as 別名]
# 或者: from portalocker import LOCK_EX [as 別名]
def write_file(filename, obj):
    file_data = 0
    while file_data is not None:
        lock = portalocker.Lock(filename, mode='a+b', flags=portalocker.LOCK_EX)
        lock.acquire()
        fh = lock.fh
        fh.seek(0)
        if len(fh.read()) is 0:
            file_data = None
        else:
            fh.seek(0)
            file_data = pickle.load(fh)
        if file_data is None:
            clear_file(fh)
            pickle.dump(obj, fh)
        lock.release() 
開發者ID:negrinho,項目名稱:deep_architect,代碼行數:18,代碼來源:file_utils.py

示例2: init_list

# 需要導入模塊: import portalocker [as 別名]
# 或者: from portalocker import LOCK_EX [as 別名]
def init_list(self, data=None):
        """
        Initialize asid_list file.
        :param data: list or a string
        :return:
        """
        file_path = os.path.join(running_path, '{sid}_list'.format(sid=self.sid))
        if not os.path.exists(file_path):
            if isinstance(data, list):
                with open(file_path, 'w') as f:
                    portalocker.lock(f, portalocker.LOCK_EX)
                    f.write(json.dumps({
                        'sids': {},
                        'total_target_num': len(data),
                    }))
            else:
                with open(file_path, 'w') as f:
                    portalocker.lock(f, portalocker.LOCK_EX)
                    f.write(json.dumps({
                        'sids': {},
                        'total_target_num': 1,
                    })) 
開發者ID:LoRexxar,項目名稱:Cobra-W,代碼行數:24,代碼來源:engine.py

示例3: list

# 需要導入模塊: import portalocker [as 別名]
# 或者: from portalocker import LOCK_EX [as 別名]
def list(self, data=None):
        file_path = os.path.join(running_path, '{sid}_list'.format(sid=self.sid))
        if data is None:
            with open(file_path, 'r') as f:
                portalocker.lock(f, portalocker.LOCK_EX)
                result = f.readline()
                return json.loads(result)
        else:
            with open(file_path, 'r+') as f:
                portalocker.lock(f, portalocker.LOCK_EX)
                result = f.read()
                if result == '':
                    result = {'sids': {}}
                else:
                    result = json.loads(result)
                result['sids'][data[0]] = data[1]
                f.seek(0)
                f.truncate()
                f.write(json.dumps(result)) 
開發者ID:LoRexxar,項目名稱:Cobra-W,代碼行數:21,代碼來源:engine.py

示例4: _do_lock

# 需要導入模塊: import portalocker [as 別名]
# 或者: from portalocker import LOCK_EX [as 別名]
def _do_lock(self):
        if self.is_locked:
            return   # already locked... recursive?
        self._open_lockfile()
        if self.stream_lock:
            for i in range(10):
                # noinspection PyBroadException
                try:
                    lock(self.stream_lock, LOCK_EX)
                    self.is_locked = True
                    break
                except Exception:
                    continue
            else:
                raise RuntimeError("Cannot acquire lock after 10 attempts")
        else:
            self._console_log("No self.stream_lock to lock", stack=True) 
開發者ID:Preston-Landers,項目名稱:concurrent-log-handler,代碼行數:19,代碼來源:__init__.py

示例5: _try_store_in_file

# 需要導入模塊: import portalocker [as 別名]
# 或者: from portalocker import LOCK_EX [as 別名]
def _try_store_in_file(self, request, response):
        try:
            if (not response.session_id or self._forget 
                or self._unchanged(response)):
                # self.clear_session_cookies()
                self.save_session_id_cookie()
                return False
            if response.session_new or not response.session_file:
                # Tests if the session sub-folder exists, if not, create it
                session_folder = os.path.dirname(response.session_filename)
                if not os.path.exists(session_folder): os.mkdir(session_folder)
                response.session_file = open(response.session_filename, 'wb')
                portalocker.lock(response.session_file, portalocker.LOCK_EX)
                response.session_locked = True
            if response.session_file:
                session_pickled = response.session_pickled or cPickle.dumps(self)
                response.session_file.write(session_pickled)
                response.session_file.truncate()
        finally:
            self._close(response)

        self.save_session_id_cookie()
        return True 
開發者ID:uwdata,項目名稱:termite-visualizations,代碼行數:25,代碼來源:globals.py

示例6: acquire

# 需要導入模塊: import portalocker [as 別名]
# 或者: from portalocker import LOCK_EX [as 別名]
def acquire(self):
        """ Acquire thread and file locks.  Re-opening log for 'degraded' mode.
        """
        # handle thread lock
        Handler.acquire(self)
        # Issue a file lock.  (This is inefficient for multiple active threads
        # within a single process. But if you're worried about high-performance,
        # you probably aren't using this log handler.)
        if self.stream_lock:
            # If stream_lock=None, then assume close() was called or something
            # else weird and ignore all file-level locks.
            if self.stream_lock.closed:
                # Daemonization can close all open file descriptors, see
                # https://bugzilla.redhat.com/show_bug.cgi?id=952929
                # Try opening the lock file again.  Should we warn() here?!?
                try:
                    self._open_lockfile()
                except Exception:
                    self.handleError(NullLogRecord())
                    # Don't try to open the stream lock again
                    self.stream_lock = None
                    return
            lock(self.stream_lock, LOCK_EX)
            # Stream will be opened as part by FileHandler.emit() 
開發者ID:zstackio,項目名稱:zstack-utility,代碼行數:26,代碼來源:concurrentlog_handler.py

示例7: __init__

# 需要導入模塊: import portalocker [as 別名]
# 或者: from portalocker import LOCK_EX [as 別名]
def __init__(self,
                 num_procs,
                 dirname='file_comm',
                 worker_queue_file='worker_queue',
                 worker_results_prefix='worker_results_'):
        # make directory where communication files are created
        try:
            os.makedirs(dirname)
        except OSError:
            pass

        # claim a rank for the process
        lock = portalocker.Lock(os.path.join(dirname, 'init'),
                                mode='a+',
                                flags=portalocker.LOCK_EX)
        lock.acquire()
        fh = lock.fh
        fh.seek(0)
        curnum = fh.read()
        if len(curnum) is 0:
            rank = 0
        else:
            rank = int(curnum)

        if rank >= num_procs:
            raise ValueError('Number of processes > the number of workers')
        fh.seek(0)
        fh.truncate(0)
        fh.write(str(rank + 1))
        lock.release()

        super(FileCommunicator, self).__init__(num_procs - 1, rank)
        self.worker_queue_file = os.path.join(dirname, worker_queue_file)
        self.worker_results_prefix = os.path.join(dirname,
                                                  worker_results_prefix)
        self.done = False 
開發者ID:negrinho,項目名稱:deep_architect,代碼行數:38,代碼來源:file_communicator.py

示例8: consume_file

# 需要導入模塊: import portalocker [as 別名]
# 或者: from portalocker import LOCK_EX [as 別名]
def consume_file(filename):
    lock = portalocker.Lock(filename, mode='a+b', flags=portalocker.LOCK_EX)
    lock.acquire()
    fh = lock.fh
    fh.seek(0)
    if len(fh.read()) is 0:
        file_data = None
    else:
        fh.seek(0)
        file_data = pickle.load(fh)
    if file_data is not None:
        clear_file(fh)
        pickle.dump(None, fh)
    lock.release()
    return file_data 
開發者ID:negrinho,項目名稱:deep_architect,代碼行數:17,代碼來源:file_utils.py

示例9: read_file

# 需要導入模塊: import portalocker [as 別名]
# 或者: from portalocker import LOCK_EX [as 別名]
def read_file(filename):
    lock = portalocker.Lock(filename, mode='a+b', flags=portalocker.LOCK_EX)
    lock.acquire()
    fh = lock.fh
    fh.seek(0)
    if len(fh.read()) is 0:
        file_data = None
    else:
        fh.seek(0)
        file_data = pickle.load(fh)
    lock.release()
    return file_data 
開發者ID:negrinho,項目名稱:deep_architect,代碼行數:14,代碼來源:file_utils.py

示例10: get

# 需要導入模塊: import portalocker [as 別名]
# 或者: from portalocker import LOCK_EX [as 別名]
def get(self, count: int=1, readOnly: bool=False, recurlvl=0):
        with open(self.FILE, "r+") as file:
            portalocker.lock(file, portalocker.LOCK_EX)
            ports = []
            while len(ports) < count:
                file.seek(0)
                port = int(file.readline())
                if readOnly:
                    return port
                port += 1
                if port > self.maxPort:
                    port = self.minPort
                file.seek(0)
                file.write(str(port))
                try:
                    checkPortAvailable(("", port))
                    ports.append(port)
                    self.logger.debug("new port dispensed: {}".format(port))
                except Exception:
                    if recurlvl < self.maxportretries:
                        self.logger.debug("port {} unavailable, trying again...".
                                          format(port))
                        recurlvl += 1
                    else:
                        self.logger.debug("port {} unavailable, max retries {} "
                                          "reached".
                                          format(port, self.maxportretries))
                        raise
            return ports 
開發者ID:hyperledger,項目名稱:indy-plenum,代碼行數:31,代碼來源:port_dispenser.py

示例11: status

# 需要導入模塊: import portalocker [as 別名]
# 或者: from portalocker import LOCK_EX [as 別名]
def status(self, data=None):
        file_path = os.path.join(running_path, '{sid}_status'.format(sid=self.sid))
        if data is None:
            with open(file_path) as f:
                portalocker.lock(f, portalocker.LOCK_EX)
                result = f.readline()
            return json.loads(result)
        else:
            data = json.dumps(data)
            with open(file_path, 'w') as f:
                portalocker.lock(f, portalocker.LOCK_EX)
                f.writelines(data) 
開發者ID:LoRexxar,項目名稱:Cobra-W,代碼行數:14,代碼來源:engine.py

示例12: data

# 需要導入模塊: import portalocker [as 別名]
# 或者: from portalocker import LOCK_EX [as 別名]
def data(self, data=None):

        file_path = os.path.abspath(running_path + '/{sid}_data'.format(sid=self.sid))

        if data is None:
            with open(file_path) as f:
                portalocker.lock(f, portalocker.LOCK_EX)
                result = f.readline()
            return json.loads(result)
        else:
            data = json.dumps(data, sort_keys=True)
            with open(file_path, 'w+') as f:
                portalocker.lock(f, portalocker.LOCK_EX)
                f.writelines(data) 
開發者ID:LoRexxar,項目名稱:Cobra-W,代碼行數:16,代碼來源:engine.py

示例13: acquire

# 需要導入模塊: import portalocker [as 別名]
# 或者: from portalocker import LOCK_EX [as 別名]
def acquire(self):
        """ Acquire thread and file locks. Also re-opening log file when running
        in 'degraded' mode. """
        # handle thread lock
        Handler.acquire(self)
        lock(self.stream_lock, LOCK_EX)
        if self.stream.closed:
            self._openFile(self.mode) 
開發者ID:harryliu,項目名稱:edwin,代碼行數:10,代碼來源:cloghandler.py

示例14: __enter__

# 需要導入模塊: import portalocker [as 別名]
# 或者: from portalocker import LOCK_EX [as 別名]
def __enter__(self) -> Optional[GpuDeviceType]:
        for gpu_id in self.candidates:
            lockfile_path = os.path.join(self.lock_dir, "sockeye.gpu{}.lock".format(gpu_id))
            try:
                lock_file = open(lockfile_path, 'w')
            except IOError:
                if errno.EACCES:
                    logger.warning("GPU {} is currently locked by a different process "
                                   "(Permission denied).".format(gpu_id))
                    continue
            try:
                # exclusive non-blocking lock
                portalocker.lock(lock_file, portalocker.LOCK_EX | portalocker.LOCK_NB)
                # got the lock, let's write our PID into it:
                lock_file.write("%d\n" % os.getpid())
                lock_file.flush()

                self._acquired_lock = True
                self.gpu_id = gpu_id
                self.lock_file = lock_file
                self.lockfile_path = lockfile_path

                logger.info("Acquired GPU {}.".format(gpu_id))

                return gpu_id
            except portalocker.LockException as e:
                # portalocker packages the original exception,
                # we dig it out and raise if unrelated to us
                if e.args[0].errno != errno.EAGAIN:  # pylint: disable=no-member
                    logger.error("Failed acquiring GPU lock.", exc_info=True)
                    raise e.args[0]
                else:
                    logger.debug("GPU {} is currently locked.".format(gpu_id))
        return None 
開發者ID:awslabs,項目名稱:sockeye,代碼行數:36,代碼來源:utils.py

示例15: __init__

# 需要導入模塊: import portalocker [as 別名]
# 或者: from portalocker import LOCK_EX [as 別名]
def __init__(self, filename, mode="rb"):
        self.filename = filename
        self.mode = mode
        self.file = None
        if "r" in mode:
            self.file = open_file(filename, mode)
            lock(self.file, LOCK_SH)
        elif "w" in mode or "a" in mode:
            self.file = open_file(filename, mode.replace("w", "a"))
            lock(self.file, LOCK_EX)
            if "a" not in mode:
                self.file.seek(0)
                self.file.truncate(0)
        else:
            raise RuntimeError("invalid LockedFile(...,mode)") 
開發者ID:web2py,項目名稱:pydal,代碼行數:17,代碼來源:portalocker.py


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