shutil.py 3.84 KB
Newer Older
1
"""Utility functions for copying files and directory trees.
2

3
XXX The functions here don't copy the resource fork or other metadata on Mac.
4 5

"""
Guido van Rossum's avatar
Guido van Rossum committed
6

Guido van Rossum's avatar
Guido van Rossum committed
7
import os
8
import sys
9
import stat
Guido van Rossum's avatar
Guido van Rossum committed
10

11 12
__all__ = ["copyfileobj","copyfile","copymode","copystat","copy","copy2",
           "copytree","rmtree"]
Guido van Rossum's avatar
Guido van Rossum committed
13

14 15 16 17 18 19 20 21
def copyfileobj(fsrc, fdst, length=16*1024):
    """copy data from file-like object fsrc to file-like object fdst"""
    while 1:
        buf = fsrc.read(length)
        if not buf:
            break
        fdst.write(buf)

Tim Peters's avatar
Tim Peters committed
22

Guido van Rossum's avatar
Guido van Rossum committed
23
def copyfile(src, dst):
24
    """Copy data from src to dst"""
25 26 27
    fsrc = None
    fdst = None
    try:
28 29
        fsrc = open(src, 'rb')
        fdst = open(dst, 'wb')
30
        copyfileobj(fsrc, fdst)
31
    finally:
32 33 34 35
        if fdst:
            fdst.close()
        if fsrc:
            fsrc.close()
Guido van Rossum's avatar
Guido van Rossum committed
36 37

def copymode(src, dst):
38
    """Copy mode bits from src to dst"""
39 40 41 42
    if hasattr(os, 'chmod'):
        st = os.stat(src)
        mode = stat.S_IMODE(st[stat.ST_MODE])
        os.chmod(dst, mode)
Guido van Rossum's avatar
Guido van Rossum committed
43 44

def copystat(src, dst):
45
    """Copy all stat info (mode bits, atime and mtime) from src to dst"""
46
    st = os.stat(src)
47
    mode = stat.S_IMODE(st[stat.ST_MODE])
48 49 50 51
    if hasattr(os, 'utime'):
        os.utime(dst, (st[stat.ST_ATIME], st[stat.ST_MTIME]))
    if hasattr(os, 'chmod'):
        os.chmod(dst, mode)
52

Guido van Rossum's avatar
Guido van Rossum committed
53 54

def copy(src, dst):
55
    """Copy data and mode bits ("cp src dst").
Tim Peters's avatar
Tim Peters committed
56

57 58 59
    The destination may be a directory.

    """
60
    if os.path.isdir(dst):
61
        dst = os.path.join(dst, os.path.basename(src))
62 63
    copyfile(src, dst)
    copymode(src, dst)
Guido van Rossum's avatar
Guido van Rossum committed
64 65

def copy2(src, dst):
66 67 68 69 70
    """Copy data and all stat info ("cp -p src dst").

    The destination may be a directory.

    """
71
    if os.path.isdir(dst):
72
        dst = os.path.join(dst, os.path.basename(src))
73 74
    copyfile(src, dst)
    copystat(src, dst)
Guido van Rossum's avatar
Guido van Rossum committed
75

76 77 78 79 80 81 82 83 84 85 86 87 88 89 90

def copytree(src, dst, symlinks=0):
    """Recursively copy a directory tree using copy2().

    The destination directory must not already exist.
    Error are reported to standard output.

    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.

    XXX Consider this example code rather than the ultimate tool.

    """
91
    names = os.listdir(src)
92
    os.mkdir(dst)
93
    for name in names:
94 95 96 97 98 99 100
        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):
101
                copytree(srcname, dstname, symlinks)
102 103 104 105 106
            else:
                copy2(srcname, dstname)
            # XXX What about devices, sockets etc.?
        except (IOError, os.error), why:
            print "Can't copy %s to %s: %s" % (`srcname`, `dstname`, str(why))
107 108 109 110 111 112 113 114 115 116 117 118

def rmtree(path, ignore_errors=0, onerror=None):
    """Recursively delete a directory tree.

    If ignore_errors is set, errors are ignored; otherwise, if
    onerror is set, it is called to handle the error; otherwise, an
    exception is raised.

    """
    cmdtuples = []
    _build_cmdtuple(path, cmdtuples)
    for cmd in cmdtuples:
119 120 121 122 123 124 125 126 127 128
        try:
            apply(cmd[0], (cmd[1],))
        except:
            exc = sys.exc_info()
            if ignore_errors:
                pass
            elif onerror:
                onerror(cmd[0], cmd[1], exc)
            else:
                raise exc[0], (exc[1][0], exc[1][1] + ' removing '+cmd[1])
129 130 131 132

# Helper for rmtree()
def _build_cmdtuple(path, cmdtuples):
    for f in os.listdir(path):
133 134 135 136
        real_f = os.path.join(path,f)
        if os.path.isdir(real_f) and not os.path.islink(real_f):
            _build_cmdtuple(real_f, cmdtuples)
        else:
137 138
            cmdtuples.append((os.remove, real_f))
    cmdtuples.append((os.rmdir, path))