【问题标题】:Random OSError 22 using shutil with unicode path使用带有 unicode 路径的 shutil 的随机 OSError 22
【发布时间】:2018-03-22 18:36:19
【问题描述】:

我目前在使用 shutil 模块时遇到问题。我正在使用以下函数递归复制文件并覆盖其他文件

def copytree(src, dst, symlinks=False, ignore=None):
    names = os.listdir(src)
    if ignore is not None:
        ignored_names = ignore(src, names)
    else:
        ignored_names = set()

    if not os.path.isdir(dst):  # This one line does the trick
        os.makedirs(dst)
    errors = []
    for name in names:
        if name in ignored_names:
            continue
        srcname = os.path.join(src, name)
        dstname = os.path.join(dst, name)
        try:
            if symlinks and os.path.islink(srcname):
                linkto = os.readlink(srcname)
                os.symlink(linkto, dstname)
            elif os.path.isdir(srcname):
                copytree(srcname, dstname, symlinks, ignore)
            else:
                # Will raise a SpecialFileError for unsupported file types
                shutil.copy2(srcname, dstname)
        # catch the Error from the recursive copytree so that we can
        # continue with other files
        except shutil.Error as err:
            errors.extend(err.args[0])
        except EnvironmentError as why:
            errors.append((srcname, dstname, str(why)))
    try:
        shutil.copystat(src, dst)
    except OSError as why:
        if WindowsError is not None and isinstance(why, WindowsError):
            # Copying file access times may fail on Windows
            pass
        else:
            errors.extend((src, dst, str(why)))
    if errors:
        raise shutil.Error(errors)

因为我有一些路径比 Windows 上的 PATH_MAX(260 个字符)长,所以我在路径的开头使用了 '\\?\'。有时shutil会返回如下错误:

shutil.Error: [
    ('\\\\?\\F:\\Jenkins_tests\\workspace\\team_workspace_tests\\sources\\master\\distrib\\folders\\file.sch_txt'),
     '\\\\?\\F:\\Jenkins_tests\\workspace\\team_workspace_tests\\sources\\master\\IMAGE\\schema\\sch_0_15.sch_txt',
     "[Errno 22] Invalid argument: '\\\\\\\\?\\\\F:\\\\Jenkins_tests\\\\workspace\\\\team_workspace_tests\\\\sources\\\\master\\\\IMAGE\\\\schema\\\\sch_0_15.sch_txt']`

但是如果我重新启动脚本,我不会有错误,或者另一个文件有错误...

也许我做错了?

【问题讨论】:

    标签: python shutil


    【解决方案1】:

    为了解决这个问题,我只需要在复制新文件之前删除硬链接。由于我有很多工作区都有指向同一个文件的硬链接,因此 copyfile 函数会尝试在它的写入模式下打开,如果它与另一个工作区同时发生,它可能无法工作。

    【讨论】:

      猜你喜欢
      • 2021-11-06
      • 1970-01-01
      • 2011-01-24
      • 1970-01-01
      • 2012-04-14
      • 2020-10-14
      • 2019-08-07
      • 1970-01-01
      相关资源
      最近更新 更多