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


Python os.O_EXCL屬性代碼示例

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


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

示例1: write_pid_to_pidfile

# 需要導入模塊: import os [as 別名]
# 或者: from os import O_EXCL [as 別名]
def write_pid_to_pidfile(pidfile_path):
    """ Write the PID in the named PID file.

        Get the numeric process ID (“PID”) of the current process
        and write it to the named file as a line of text.

        """
    open_flags = (os.O_CREAT | os.O_EXCL | os.O_WRONLY)
    open_mode = 0o644
    pidfile_fd = os.open(pidfile_path, open_flags, open_mode)
    pidfile = os.fdopen(pidfile_fd, 'w')

    # According to the FHS 2.3 section on PID files in /var/run:
    #
    #   The file must consist of the process identifier in
    #   ASCII-encoded decimal, followed by a newline character. For
    #   example, if crond was process number 25, /var/run/crond.pid
    #   would contain three characters: two, five, and newline.

    pid = os.getpid()
    pidfile.write("%s\n" % pid)
    pidfile.close() 
開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:24,代碼來源:pidlockfile.py

示例2: create_cleanup_lock

# 需要導入模塊: import os [as 別名]
# 或者: from os import O_EXCL [as 別名]
def create_cleanup_lock(p):
    """crates a lock to prevent premature folder cleanup"""
    lock_path = get_lock_path(p)
    try:
        fd = os.open(str(lock_path), os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o644)
    except OSError as e:
        if e.errno == errno.EEXIST:
            raise EnvironmentError(
                "cannot create lockfile in {path}".format(path=p)
            ) from e

        else:
            raise
    else:
        pid = os.getpid()
        spid = str(pid).encode()
        os.write(fd, spid)
        os.close(fd)
        if not lock_path.is_file():
            raise EnvironmentError("lock path got renamed after successful creation")
        return lock_path 
開發者ID:sofia-netsurv,項目名稱:python-netsurv,代碼行數:23,代碼來源:pathlib.py

示例3: touch

# 需要導入模塊: import os [as 別名]
# 或者: from os import O_EXCL [as 別名]
def touch(self, mode=0o666, exist_ok=True):
        """
        Create this file with the given access mode, if it doesn't exist.
        """
        if self._closed:
            self._raise_closed()
        if exist_ok:
            # First try to bump modification time
            # Implementation note: GNU touch uses the UTIME_NOW option of
            # the utimensat() / futimens() functions.
            try:
                self._accessor.utime(self, None)
            except OSError:
                # Avoid exception chaining
                pass
            else:
                return
        flags = os.O_CREAT | os.O_WRONLY
        if not exist_ok:
            flags |= os.O_EXCL
        fd = self._raw_open(flags, mode)
        os.close(fd) 
開發者ID:sofia-netsurv,項目名稱:python-netsurv,代碼行數:24,代碼來源:__init__.py

示例4: test_file_create_lock

# 需要導入模塊: import os [as 別名]
# 或者: from os import O_EXCL [as 別名]
def test_file_create_lock(backend, mocker):
    key = 'test.task.key'
    timeout = 3600
    open_mock = mocker.patch('celery_once.backends.file.os.open')
    mtime_mock = mocker.patch('celery_once.backends.file.os.path.getmtime')
    utime_mock = mocker.patch('celery_once.backends.file.os.utime')
    close_mock = mocker.patch('celery_once.backends.file.os.close')
    expected_lock_path = os.path.join(TEST_LOCATION,
                                      key_to_lock_name(key))
    ret = backend.raise_or_lock(key, timeout)

    assert open_mock.call_count == 1
    assert open_mock.call_args[0] == (
        expected_lock_path,
        os.O_CREAT | os.O_EXCL,
    )
    assert utime_mock.called is False
    assert close_mock.called is True
    assert ret is None 
開發者ID:cameronmaske,項目名稱:celery-once,代碼行數:21,代碼來源:test_file.py

示例5: raise_or_lock

# 需要導入模塊: import os [as 別名]
# 或者: from os import O_EXCL [as 別名]
def raise_or_lock(self, key, timeout):
        """
        Check the lock file and create one if it does not exist.
        """
        lock_path = self._get_lock_path(key)
        try:
            # Create lock file, raise exception if it exists
            fd = os.open(lock_path, os.O_CREAT | os.O_EXCL)
        except OSError as error:
            if error.errno == errno.EEXIST:
                # File already exists, check its modification time
                mtime = os.path.getmtime(lock_path)
                ttl = mtime + timeout - time.time()
                if ttl > 0:
                    raise AlreadyQueued(ttl)
                else:
                    # Update modification time if timeout happens
                    os.utime(lock_path, None)
                    return
            else:
                # Re-raise unexpected OSError
                raise
        else:
            os.close(fd) 
開發者ID:cameronmaske,項目名稱:celery-once,代碼行數:26,代碼來源:file.py

示例6: createTempFile

# 需要導入模塊: import os [as 別名]
# 或者: from os import O_EXCL [as 別名]
def createTempFile(self):
        """
        Create a temporary file to hold the message as it is being transferred.
        """
        attr = (os.O_RDWR | os.O_CREAT | os.O_EXCL
                | getattr(os, "O_NOINHERIT", 0)
                | getattr(os, "O_NOFOLLOW", 0))
        tries = 0
        self.fh = -1
        while True:
            self.tmpname = os.path.join(self.mbox.path, "tmp", _generateMaildirName())
            try:
                self.fh = self.osopen(self.tmpname, attr, 0o600)
                return None
            except OSError:
                tries += 1
                if tries > 500:
                    self.defer.errback(RuntimeError("Could not create tmp file for %s" % self.mbox.path))
                    self.defer = None
                    return None 
開發者ID:proxysh,項目名稱:Safejumper-for-Desktop,代碼行數:22,代碼來源:maildir.py

示例7: lock

# 需要導入模塊: import os [as 別名]
# 或者: from os import O_EXCL [as 別名]
def lock(self):
        '''Lock a file and return a file descriptor.

Need to call unlock to release the lock.
        '''
        self._validate_lockname()
        count = 0
        while True:
            try:
                self._lock_fd = os.open(self._lockname,
                                        os.O_CREAT | os.O_EXCL | os.O_RDWR)
                break
            except OSError as xcpt:
                if xcpt.errno != errno.EEXIST:
                    raise
                if count % 30 == 0:
                    LOG.debug('waiting for lock %s' % self._lockname)
                time.sleep(1)
                count += 1
        return self._lock_fd 
開發者ID:redhat-cip,項目名稱:hardware,代碼行數:22,代碼來源:state.py

示例8: get_login_params

# 需要導入模塊: import os [as 別名]
# 或者: from os import O_EXCL [as 別名]
def get_login_params():
    import getpass
    import json
    import os
    import tempfile

    filename = os.path.join(
        tempfile.gettempdir(), 'votrlogin-' + getpass.getuser())

    if os.path.exists(filename):
        with open(filename) as f:
            return json.load(f)

    username = input('AIS username: ')
    password = getpass.getpass('AIS password: ')
    params = dict(type='cosignpassword', username=username, password=password)

    fd = os.open(filename, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
    with open(fd, 'w') as f:
        json.dump(params, f)

    return params 
開發者ID:fmfi-svt,項目名稱:votr,代碼行數:24,代碼來源:nbenv.py

示例9: acquire

# 需要導入模塊: import os [as 別名]
# 或者: from os import O_EXCL [as 別名]
def acquire(self, blocking=True):
        """Acquire the lock if possible.

        If the lock is in use and ``blocking`` is ``False``, return
        ``False``.

        Otherwise, check every `self.delay` seconds until it acquires
        lock or exceeds `self.timeout` and raises an exception.

        """
        start = time.time()
        while True:
            try:
                fd = os.open(self.lockfile, os.O_CREAT | os.O_EXCL | os.O_RDWR)
                with os.fdopen(fd, 'w') as fd:
                    fd.write('{0}'.format(os.getpid()))
                break
            except OSError as err:
                if err.errno != errno.EEXIST:  # pragma: no cover
                    raise
                if self.timeout and (time.time() - start) >= self.timeout:
                    raise AcquisitionError('Lock acquisition timed out.')
                if not blocking:
                    return False
                time.sleep(self.delay)

        self._locked = True
        return True 
開發者ID:danielecook,項目名稱:Quiver-alfred,代碼行數:30,代碼來源:workflow.py

示例10: create_file

# 需要導入模塊: import os [as 別名]
# 或者: from os import O_EXCL [as 別名]
def create_file(self, prefix, filename):
        full_file_name = "%s%s.txt" % (prefix, filename)
        file_path = "%s%s" % (self.settings.get_data_folder_path(), full_file_name)
        try:
            file = os_open(file_path, O_CREAT | O_EXCL)
            os_close(file)
            return full_file_name
        except IOError as e:
            log.error("Failed to create a new file! Error: %s", e) 
開發者ID:thingsboard,項目名稱:thingsboard-gateway,代碼行數:11,代碼來源:event_storage_writer.py

示例11: _secure_open_write

# 需要導入模塊: import os [as 別名]
# 或者: from os import O_EXCL [as 別名]
def _secure_open_write(filename, fmode):
    # We only want to write to this file, so open it in write only mode
    flags = os.O_WRONLY

    # os.O_CREAT | os.O_EXCL will fail if the file already exists, so we only
    #  will open *new* files.
    # We specify this because we want to ensure that the mode we pass is the
    # mode of the file.
    flags |= os.O_CREAT | os.O_EXCL

    # Do not follow symlinks to prevent someone from making a symlink that
    # we follow and insecurely open a cache file.
    if hasattr(os, "O_NOFOLLOW"):
        flags |= os.O_NOFOLLOW

    # On Windows we'll mark this file as binary
    if hasattr(os, "O_BINARY"):
        flags |= os.O_BINARY

    # Before we open our file, we want to delete any existing file that is
    # there
    try:
        os.remove(filename)
    except (IOError, OSError):
        # The file must not exist already, so we can just skip ahead to opening
        pass

    # Open our file, the use of os.O_CREAT | os.O_EXCL will ensure that if a
    # race condition happens between the os.remove and this line, that an
    # error will be raised. Because we utilize a lockfile this should only
    # happen if someone is attempting to attack us.
    fd = os.open(filename, flags, fmode)
    try:
        return os.fdopen(fd, "wb")
    except:
        # An error occurred wrapping our FD in a file object
        os.close(fd)
        raise 
開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:40,代碼來源:file_cache.py

示例12: _create_ssh_key

# 需要導入模塊: import os [as 別名]
# 或者: from os import O_EXCL [as 別名]
def _create_ssh_key(keyfile):
    """ Create the public and private ssh keys.

    The specified file name will be the private key and the public one will
    be in a similar file name ending with a '.pub'.

    """
    private_key = rsa.generate_private_key(
        public_exponent=65537, key_size=4096, backend=default_backend()
    )

    private_pem = private_key.private_bytes(
        encoding=serialization.Encoding.PEM,
        format=serialization.PrivateFormat.TraditionalOpenSSL,
        encryption_algorithm=serialization.NoEncryption(),
    )
    with os.fdopen(
        os.open(keyfile, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600), "wb"
    ) as stream:
        stream.write(private_pem)

    public_key = private_key.public_key()
    public_pem = _serialize_public_ssh_key(public_key)
    if public_pem:
        with open(keyfile + ".pub", "wb") as stream:
            stream.write(public_pem) 
開發者ID:Pagure,項目名稱:pagure,代碼行數:28,代碼來源:tasks_mirror.py

示例13: __linux_start_process__

# 需要導入模塊: import os [as 別名]
# 或者: from os import O_EXCL [as 別名]
def __linux_start_process__(self, binary_path, task_key, gl_version, verbose,
                                show_viewport=True):
        import posix_ipc
        out_stream = sys.stdout if verbose else open(os.devnull, 'w')
        loading_semaphore = \
            posix_ipc.Semaphore('/HOLODECK_LOADING_SEM' + self._uuid, os.O_CREAT | os.O_EXCL,
                                initial_value=0)
        # Copy the environment variables and remove the DISPLAY variable to hide viewport
        # https://answers.unrealengine.com/questions/815764/in-the-release-notes-it-says-the-engine-can-now-cr.html?sort=oldest
        environment = dict(os.environ.copy())
        if not show_viewport and 'DISPLAY' in environment:
            del environment['DISPLAY']
        self._world_process = \
            subprocess.Popen([binary_path, task_key, '-HolodeckOn', '-opengl' + str(gl_version),
                              '-LOG=HolodeckLog.txt', '-ForceRes', '-ResX=' + str(self._window_size[1]),
                              '-ResY=' + str(self._window_size[0]), '--HolodeckUUID=' + self._uuid,
                              '-TicksPerSec=' + str(self._ticks_per_sec)],
                             stdout=out_stream,
                             stderr=out_stream,
                             env=environment)

        atexit.register(self.__on_exit__)

        try:
            loading_semaphore.acquire(10)
        except posix_ipc.BusyError:
            raise HolodeckException("Timed out waiting for binary to load. Ensure that holodeck is "
                                    "not being run with root priveleges.")
        loading_semaphore.unlink() 
開發者ID:BYU-PCCL,項目名稱:holodeck,代碼行數:31,代碼來源:environments.py


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