【问题标题】:cp -r from_dir/* to_dir with pythoncp -r from_dir/* to_dir 与 python
【发布时间】:2011-04-27 09:10:09
【问题描述】:

有没有一种简单的方法可以用 python 模拟命令cp -r from_dir/* to_dirshutil.copytree 不适合,因为 to_dir 存在。

【问题讨论】:

    标签: python directory shutil


    【解决方案1】:

    看一下shutil.copytree的源码,改编使用:

    def copytree(src, dst, symlinks=False, ignore=None):
        """Recursively copy a directory tree using copy2().
    
        The destination directory must not already exist.
        If exception(s) occur, an Error is raised with a list of reasons.
    
        If the optional symlinks flag is true, symbolic links in the
        source tree result in symbolic links in the destination tree; if
        it is false, the contents of the files pointed to by symbolic
        links are copied.
    
        The optional ignore argument is a callable. If given, it
        is called with the `src` parameter, which is the directory
        being visited by copytree(), and `names` which is the list of
        `src` contents, as returned by os.listdir():
    
            callable(src, names) -> ignored_names
    
        Since copytree() is called recursively, the callable will be
        called once for each directory that is copied. It returns a
        list of names relative to the `src` directory that should
        not be copied.
    
        XXX Consider this example code rather than the ultimate tool.
    
        """
        names = os.listdir(src)
        if ignore is not None:
            ignored_names = ignore(src, names)
        else:
            ignored_names = set()
    
        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:
                    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
    

    【讨论】:

      【解决方案2】:

      您只需使用正确的名称(或相同的名称)copytree

      shutil.copytree("/path/from_dir","/destination/from_dir")
      

      【讨论】:

      • 不一样,我要复制目录的内容,不是目录
      【解决方案3】:
      import glob
      import subprocess
      
      subprocess.check_call(["cp", "-rt", "to_dir"] + glob.glob("from_dir/*"))
      

      有时自己直接在 Python 中完成所有事情会很好;再说一次,调用你知道如何控制和知道如何工作的命令通常会更好。

      当需求发生变化时,我会毫不犹豫地重写此 if,但在此之前,它简短易读——更多的时间最好花在更大的问题上。他们可能如何改变的一个很好的例子是报告一个错误:你没有说什么,但一旦需要,我不会解析 cp 的输出。

      【讨论】:

      • 另外值得一提的是cp 可能会生成您可能不想要的输出。考虑将 stdout/stderr 发送到/dev/null
      • 这个和我现在做的很像,但是不便携
      • @wiso:你能用你的目标平台/环境更新这个问题吗?
      • @roger: 平台/环境独立
      猜你喜欢
      • 2015-02-21
      • 2015-01-30
      • 2011-01-17
      • 2015-11-15
      • 2011-05-02
      • 1970-01-01
      • 2011-02-27
      • 1970-01-01
      • 2017-09-18
      相关资源
      最近更新 更多