Guido van Rossum | c636014 | 1990-10-13 19:23:40 +0000 | [diff] [blame] | 1 | # Module 'shutil' -- utility functions usable in a shell-like program |
| 2 | |
| 3 | import posix |
| 4 | import path |
| 5 | |
| 6 | MODEBITS = 010000 # Lower 12 mode bits |
| 7 | # Change this to 01000 (9 mode bits) to avoid copying setuid etc. |
| 8 | |
| 9 | # Copy data from src to dst |
| 10 | # |
| 11 | def copyfile(src, dst): |
| 12 | fsrc = open(src, 'r') |
| 13 | fdst = open(dst, 'w') |
| 14 | while 1: |
| 15 | buf = fsrc.read(16*1024) |
| 16 | if not buf: break |
| 17 | fdst.write(buf) |
| 18 | |
| 19 | # Copy mode bits from src to dst |
| 20 | # |
| 21 | def copymode(src, dst): |
| 22 | st = posix.stat(src) |
| 23 | mode = divmod(st[0], MODEBITS)[1] |
| 24 | posix.chmod(dst, mode) |
| 25 | |
| 26 | # Copy all stat info (mode bits, atime and mtime) from src to dst |
| 27 | # |
| 28 | def copystat(src, dst): |
| 29 | st = posix.stat(src) |
| 30 | mode = divmod(st[0], MODEBITS)[1] |
| 31 | posix.chmod(dst, mode) |
| 32 | posix.utimes(dst, st[7:9]) |
| 33 | |
| 34 | # Copy data and mode bits ("cp src dst") |
| 35 | # |
| 36 | def copy(src, dst): |
| 37 | copyfile(src, dst) |
| 38 | copymode(src, dst) |
| 39 | |
| 40 | # Copy data and all stat info ("cp -p src dst") |
| 41 | # |
| 42 | def copy2(src, dst): |
| 43 | copyfile(src, dst) |
| 44 | copystat(src, dst) |
| 45 | |
| 46 | # Recursively copy a directory tree. |
| 47 | # The destination must not already exist. |
| 48 | # |
| 49 | def copytree(src, dst): |
| 50 | names = posix.listdir(src) |
| 51 | posix.mkdir(dst, 0777) |
| 52 | dot_dotdot = '.', '..' |
| 53 | for name in names: |
| 54 | if name not in dot_dotdot: |
Guido van Rossum | 784ca6c | 1991-08-16 13:28:23 +0000 | [diff] [blame] | 55 | srcname = path.join(src, name) |
| 56 | dstname = path.join(dst, name) |
Guido van Rossum | c636014 | 1990-10-13 19:23:40 +0000 | [diff] [blame] | 57 | #print 'Copying', srcname, 'to', dstname |
| 58 | try: |
| 59 | #if path.islink(srcname): |
| 60 | # linkto = posix.readlink(srcname) |
| 61 | # posix.symlink(linkto, dstname) |
| 62 | #elif path.isdir(srcname): |
| 63 | if path.isdir(srcname): |
| 64 | copytree(srcname, dstname) |
| 65 | else: |
| 66 | copy2(srcname, dstname) |
| 67 | # XXX What about devices, sockets etc.? |
| 68 | except posix.error, why: |
| 69 | print 'Could not copy', srcname, 'to', dstname, |
| 70 | print '(', why[1], ')' |