随机OSError 22使用带有unicode路径的shutil

2024-09-26 22:42:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前在使用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上的最大路径长(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']`

但是如果我重新启动脚本,我将没有错误,或者在另一个文件上有错误。。。你知道吗

也许我弄错了?你知道吗


Tags: pathsrcifnamesostestsworkspacedst
1条回答
网友
1楼 · 发布于 2024-09-26 22:42:45

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

相关问题 更多 >

    热门问题