blob: d3521eccf006ce64d95f1b3eadca1a273cc8aa3b [file] [log] [blame]
Guido van Rossumc6360141990-10-13 19:23:40 +00001# Module 'shutil' -- utility functions usable in a shell-like program
2
3import posix
4import path
5
6MODEBITS = 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#
11def 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#
21def 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#
28def 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#
36def copy(src, dst):
37 copyfile(src, dst)
38 copymode(src, dst)
39
40# Copy data and all stat info ("cp -p src dst")
41#
42def 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#
49def 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 Rossum784ca6c1991-08-16 13:28:23 +000055 srcname = path.join(src, name)
56 dstname = path.join(dst, name)
Guido van Rossumc6360141990-10-13 19:23:40 +000057 #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], ')'