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


Python errno.EEXIST屬性代碼示例

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


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

示例1: _rename_over_existing

# 需要導入模塊: import errno [as 別名]
# 或者: from errno import EEXIST [as 別名]
def _rename_over_existing(src, dest):
    try:
        # On Windows, this will throw EEXIST, on Linux it won't.
        os.rename(src, dest)
    except IOError as err:
        if err.errno == errno.EEXIST:
            # Clearly this song-and-dance is not in fact atomic,
            # but if something goes wrong putting the new file in
            # place at least the backup file might still be
            # around.
            backup = "{0}.bak-{1}".format(dest, str(uuid.uuid4()))
            os.rename(dest, backup)
            try:
                os.rename(src, dest)
            except Exception as err:
                os.rename(backup, dest)
                raise err
            finally:
                try:
                    os.remove(backup)
                except Exception as err:
                    pass 
開發者ID:ContinuumIO,項目名稱:ciocheck,代碼行數:24,代碼來源:utils.py

示例2: gen_data

# 需要導入模塊: import errno [as 別名]
# 或者: from errno import EEXIST [as 別名]
def gen_data(seq_len, start_range, end_range):
    if not os.path.exists(DATA_DIR):
        try:
            logging.info('create directory %s', DATA_DIR)
            os.makedirs(DATA_DIR)
        except OSError as exc:
            if exc.errno != errno.EEXIST:
                raise OSError('failed to create ' + DATA_DIR)
    vocab = [str(x) for x in range(start_range, end_range)]
    sw_train = open(os.path.join(DATA_DIR, TRAIN_FILE), "w")
    sw_test = open(os.path.join(DATA_DIR, TEST_FILE), "w")
    sw_valid = open(os.path.join(DATA_DIR, VALID_FILE), "w")

    for i in range(1000000):
        seq = " ".join([vocab[random.randint(0, len(vocab) - 1)] for j in range(seq_len)])
        k = i % 50
        if k == 0:
            sw_test.write(seq + "\n")
        elif k == 1:
            sw_valid.write(seq + "\n")
        else:
            sw_train.write(seq + "\n")

    sw_train.close()
    sw_test.close() 
開發者ID:awslabs,項目名稱:dynamic-training-with-apache-mxnet-on-aws,代碼行數:27,代碼來源:lstm_sort.py

示例3: makedirs

# 需要導入模塊: import errno [as 別名]
# 或者: from errno import EEXIST [as 別名]
def makedirs(p):
    """
    Recursive directory creation (like mkdir -p).
    Returns True if the path is successfully created, False if it existed
    already, and raises an OSError on other error conditions.
    """
    try:
        os.makedirs(p)
        return True
    except OSError as e:
        # EEXIST is fine (directory already existed).  We also occasionally get
        # EROFS when making directories in SNAP_COMMON. I am not quite sure
        # what is going on there. Re-raise any other errors.
        if e.errno == errno.EEXIST:
            pass
        elif e.errno == errno.EROFS:
            print("Read-only filesystem error occurred while making {}".format(p))
        else:
            raise e
    return False 
開發者ID:ParadropLabs,項目名稱:Paradrop,代碼行數:22,代碼來源:pdosq.py

示例4: load_file

# 需要導入模塊: import errno [as 別名]
# 或者: from errno import EEXIST [as 別名]
def load_file(filename):
    """
    Function to load datafiles, it returns a list of Todo
    """
    if not os.path.exists(os.path.dirname(filename)) and '/' in filename:
        try:
            os.makedirs(os.path.dirname(filename))
        except OSError as exc: # Guard against race condition
            if exc.errno != errno.EEXIST:
                raise
        return fabric.TodoWrapper()

    if os.path.isfile(filename):
        with open(filename, 'r+') as data_file:
            read_data = data_file.read()
            return list_decoder(json.loads(read_data))
    else:
        with open(filename, 'w') as data_file:
            return fabric.TodoWrapper() 
開發者ID:xypnox,項目名稱:todxpy,代碼行數:21,代碼來源:filehandler.py

示例5: rename

# 需要導入模塊: import errno [as 別名]
# 或者: from errno import EEXIST [as 別名]
def rename(src, dst):
        # Try atomic or pseudo-atomic rename
        if _rename(src, dst):
            return
        # Fall back to "move away and replace"
        try:
            os.rename(src, dst)
        except OSError as e:
            if e.errno != errno.EEXIST:
                raise
            old = "%s-%08x" % (dst, random.randint(0, sys.maxint))
            os.rename(dst, old)
            os.rename(src, dst)
            try:
                os.unlink(old)
            except Exception:
                pass 
開發者ID:jojoin,項目名稱:cutout,代碼行數:19,代碼來源:posixemulation.py

示例6: _store_new_measures

# 需要導入模塊: import errno [as 別名]
# 或者: from errno import EEXIST [as 別名]
def _store_new_measures(self, metric_id, data):
        tmpfile = tempfile.NamedTemporaryFile(
            prefix='gnocchi', dir=self.basepath_tmp,
            delete=False)
        tmpfile.write(data)
        tmpfile.close()
        path = self._build_measure_path(metric_id, True)
        while True:
            try:
                os.rename(tmpfile.name, path)
                break
            except OSError as e:
                if e.errno != errno.ENOENT:
                    raise
                try:
                    os.mkdir(self._build_measure_path(metric_id))
                except OSError as e:
                    # NOTE(jd) It's possible that another process created the
                    # path just before us! In this case, good for us, let's do
                    # nothing then! (see bug #1475684)
                    if e.errno != errno.EEXIST:
                        raise 
開發者ID:gnocchixyz,項目名稱:gnocchi,代碼行數:24,代碼來源:file.py

示例7: _delete_measures_files_for_metric

# 需要導入模塊: import errno [as 別名]
# 或者: from errno import EEXIST [as 別名]
def _delete_measures_files_for_metric(self, metric_id, files):
        for f in files:
            try:
                os.unlink(self._build_measure_path(metric_id, f))
            except OSError as e:
                # Another process deleted it in the meantime, no prob'
                if e.errno != errno.ENOENT:
                    raise
        try:
            os.rmdir(self._build_measure_path(metric_id))
        except OSError as e:
            # ENOENT: ok, it has been removed at almost the same time
            #         by another process
            # ENOTEMPTY: ok, someone pushed measure in the meantime,
            #            we'll delete the measures and directory later
            # EEXIST: some systems use this instead of ENOTEMPTY
            if e.errno not in (errno.ENOENT, errno.ENOTEMPTY, errno.EEXIST):
                raise 
開發者ID:gnocchixyz,項目名稱:gnocchi,代碼行數:20,代碼來源:file.py

示例8: __call__

# 需要導入模塊: import errno [as 別名]
# 或者: from errno import EEXIST [as 別名]
def __call__(self, dirname):
    """Makes a directory.

    Args:
      * dirname (str) - Directory to make (abs or relative).
    """
    if dirname in self.made_dirs:
      return
    toks = dirname.split(os.path.sep)
    try:
      os.makedirs(dirname)
    except OSError as ex:
      if ex.errno != errno.EEXIST:
        raise
    curpath = toks[0] + os.path.sep
    for tok in toks[1:]:
      curpath = os.path.join(curpath, tok)
      self.made_dirs.add(curpath) 
開發者ID:luci,項目名稱:recipes-py,代碼行數:20,代碼來源:proto_support.py

示例9: mkdir_p

# 需要導入模塊: import errno [as 別名]
# 或者: from errno import EEXIST [as 別名]
def mkdir_p(path):
    """mkdir_p(path) - Make the "path" directory, if it does not exist; this
    will also make directories for any missing parent directories."""
    import errno

    if not path or os.path.exists(path):
        return

    parent = os.path.dirname(path)
    if parent != path:
        mkdir_p(parent)

    try:
        os.mkdir(path)
    except OSError as e:
        # Ignore EEXIST, which may occur during a race condition.
        if e.errno != errno.EEXIST:
            raise 
開發者ID:llvm,項目名稱:llvm-zorg,代碼行數:20,代碼來源:shell.py

示例10: _set_project

# 需要導入模塊: import errno [as 別名]
# 或者: from errno import EEXIST [as 別名]
def _set_project():
    """Sets the maya project to the current Session's work directory.

    Returns:
        None

    """
    workdir = api.Session["AVALON_WORKDIR"]

    try:
        os.makedirs(workdir)
    except OSError as e:
        # An already existing working directory is fine.
        if e.errno == errno.EEXIST:
            pass
        else:
            raise

    cmds.workspace(workdir, openWorkspace=True) 
開發者ID:getavalon,項目名稱:core,代碼行數:21,代碼來源:pipeline.py

示例11: mkdir_p

# 需要導入模塊: import errno [as 別名]
# 或者: from errno import EEXIST [as 別名]
def mkdir_p(d):
    """ Make a directory, ignoring error if it exists (i.e., ``mkdir -p``)

    Args:
        d (str): directory path to create

    Raises:
        OSError: Raise OSError if cannot create directory for reasons other
            than it existing already (errno 13 "EEXIST")
    """
    try:
        os.makedirs(d)
    except OSError as err:
        # File exists
        if err.errno == errno.EEXIST:
            pass
        else:
            raise err 
開發者ID:ceholden,項目名稱:yatsm,代碼行數:20,代碼來源:helpers.py

示例12: rename

# 需要導入模塊: import errno [as 別名]
# 或者: from errno import EEXIST [as 別名]
def rename(src, dst):
        # Try atomic or pseudo-atomic rename
        if _rename(src, dst):
            return
        # Fall back to "move away and replace"
        try:
            os.rename(src, dst)
        except OSError as e:
            if e.errno != errno.EEXIST:
                raise
            old = "%s-%08x" % (dst, random.randint(0, sys.maxsize))
            os.rename(dst, old)
            os.rename(src, dst)
            try:
                os.unlink(old)
            except Exception:
                pass 
開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:19,代碼來源:posixemulation.py

示例13: test_atomic_write_in_pwd

# 需要導入模塊: import errno [as 別名]
# 或者: from errno import EEXIST [as 別名]
def test_atomic_write_in_pwd(tmpdir):
    orig_curdir = os.getcwd()
    try:
        os.chdir(str(tmpdir))
        fname = 'ha'
        for i in range(2):
            with atomic_write(str(fname), overwrite=True) as f:
                f.write('hoho')

        with pytest.raises(OSError) as excinfo:
            with atomic_write(str(fname), overwrite=False) as f:
                f.write('haha')

        assert excinfo.value.errno == errno.EEXIST

        assert open(fname).read() == 'hoho'
        assert len(tmpdir.listdir()) == 1
    finally:
        os.chdir(orig_curdir) 
開發者ID:untitaker,項目名稱:python-atomicwrites,代碼行數:21,代碼來源:test_atomicwrites.py

示例14: initialize

# 需要導入模塊: import errno [as 別名]
# 或者: from errno import EEXIST [as 別名]
def initialize():
    global config, parser
    from .util.printing import BOLD, RED, ENDC
    config = AegeaConfig(__name__, use_yaml=True, save_on_exit=False)
    if not os.path.exists(config.config_files[2]):
        config_dir = os.path.dirname(os.path.abspath(config.config_files[2]))
        try:
            os.makedirs(config_dir)
        except OSError as e:
            if not (e.errno == errno.EEXIST and os.path.isdir(config_dir)):
                raise
        shutil.copy(os.path.join(os.path.dirname(__file__), "user_config.yml"), config.config_files[2])
        logger.info("Wrote new config file %s with default values", config.config_files[2])
        config = AegeaConfig(__name__, use_yaml=True, save_on_exit=False)

    parser = argparse.ArgumentParser(
        description="{}: {}".format(BOLD() + RED() + __name__.capitalize() + ENDC(), fill(__doc__.strip())),
        formatter_class=AegeaHelpFormatter
    )
    parser.add_argument("--version", action="version", version="%(prog)s {}\n{} {}\n{}".format(
        __version__,
        platform.python_implementation(),
        platform.python_version(),
        platform.platform()
    ))

    def help(args):
        parser.print_help()
    register_parser(help) 
開發者ID:kislyuk,項目名稱:aegea,代碼行數:31,代碼來源:__init__.py

示例15: makedirs

# 需要導入模塊: import errno [as 別名]
# 或者: from errno import EEXIST [as 別名]
def makedirs(name, mode=0o777, exist_ok=False):
        try:
            os.makedirs(name, mode)
        except OSError as e:
            if not (exist_ok and e.errno == errno.EEXIST and os.path.isdir(name)):
                raise 
開發者ID:kislyuk,項目名稱:aegea,代碼行數:8,代碼來源:compat.py


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