Question

Y at-il un moyen facile d'imiter la commande cp -r from_dir/* to_dir avec python? shutil.copytree ne convient pas, car il existe to_dir.

Était-ce utile?

La solution

Jetez un oeil au code source de shutil.copytree, l'adapter et de l'utilisation:

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

Autres conseils

il vous suffit de copytree le nom correct (ou même nom)

shutil.copytree("/path/from_dir","/destination/from_dir")
import glob
import subprocess

subprocess.check_call(["cp", "-rt", "to_dir"] + glob.glob("from_dir/*"))

Parfois, il est agréable de faire tout directement en Python vous; là encore, il est souvent plus agréable de simplement appeler la commande que vous savez comment contrôler et connaître des œuvres.

Je ne hésite pas à réécrire cette si lorsque les exigences de changement, mais jusque-là, il est court et facile à lire - plus de temps est mieux dépensé sur de plus gros problèmes. Un bon exemple de la façon dont ils pourraient changer signale une erreur. Vous avez rien dit à ce sujet, mais je ne serais pas la sortie analyse pas cp une fois ce qui est nécessaire

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top