Chinaunix首页 | 论坛 | 博客
  • 博客访问: 49045
  • 博文数量: 5
  • 博客积分: 15
  • 博客等级: 民兵
  • 技术积分: 83
  • 用 户 组: 普通用户
  • 注册时间: 2010-07-03 00:15
文章分类

全部博文(5)

文章存档

2014年(5)

我的朋友

分类: 系统运维

2014-10-24 13:05:37

最近在使用python来管理Linux,在编写代码时发现shutil中copytree2函数的限制比较多,不方便使用。
修改后的支持软连接拷贝,拷贝时自动补全路径。

def copytree2(src, dst, symlinks=True, 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):
  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):
    if os.path.islink(dstname):
     os.remove(dstname)
                linkto = os.readlink(srcname)
                os.symlink(linkto, dstname)
            elif os.path.isdir(srcname):
                copytree2(srcname, dstname, symlinks, ignore)
            else:
    if os.path.isfile(dstname):
     os.remove(dstname)
                copy2(srcname, dstname)
            # XXX What about devices, sockets etc.?
        except (IOError, os.error), why:
            errors.append((srcname, dstname, str(why)))
        # catch the Error from the recursive copytree so that we can
        # continue with other files
        except Error, err:
            errors.extend(err.args[0])
    try:
        copystat(src, dst)
    except OSError, 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 Error, errors

阅读(1097) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~