1 """Utility functions for copying files and directory trees.
3 XXX The functions here don't copy the resource fork or other metadata on Mac.
12 def copyfileobj(fsrc
, fdst
, length
=16*1024):
13 """copy data from file-like object fsrc to file-like object fdst"""
15 buf
= fsrc
.read(length
)
21 def copyfile(src
, dst
):
22 """Copy data from src to dst"""
26 fsrc
= open(src
, 'rb')
27 fdst
= open(dst
, 'wb')
28 copyfileobj(fsrc
, fdst
)
35 def copymode(src
, dst
):
36 """Copy mode bits from src to dst"""
38 mode
= stat
.S_IMODE(st
[stat
.ST_MODE
])
41 def copystat(src
, dst
):
42 """Copy all stat info (mode bits, atime and mtime) from src to dst"""
44 mode
= stat
.S_IMODE(st
[stat
.ST_MODE
])
45 os
.utime(dst
, (st
[stat
.ST_ATIME
], st
[stat
.ST_MTIME
]))
50 """Copy data and mode bits ("cp src dst").
52 The destination may be a directory.
55 if os
.path
.isdir(dst
):
56 dst
= os
.path
.join(dst
, os
.path
.basename(src
))
61 """Copy data and all stat info ("cp -p src dst").
63 The destination may be a directory.
66 if os
.path
.isdir(dst
):
67 dst
= os
.path
.join(dst
, os
.path
.basename(src
))
72 def copytree(src
, dst
, symlinks
=0):
73 """Recursively copy a directory tree using copy2().
75 The destination directory must not already exist.
76 Error are reported to standard output.
78 If the optional symlinks flag is true, symbolic links in the
79 source tree result in symbolic links in the destination tree; if
80 it is false, the contents of the files pointed to by symbolic
83 XXX Consider this example code rather than the ultimate tool.
86 names
= os
.listdir(src
)
89 srcname
= os
.path
.join(src
, name
)
90 dstname
= os
.path
.join(dst
, name
)
92 if symlinks
and os
.path
.islink(srcname
):
93 linkto
= os
.readlink(srcname
)
94 os
.symlink(linkto
, dstname
)
95 elif os
.path
.isdir(srcname
):
96 copytree(srcname
, dstname
, symlinks
)
98 copy2(srcname
, dstname
)
99 # XXX What about devices, sockets etc.?
100 except (IOError, os
.error
), why
:
101 print "Can't copy %s to %s: %s" % (`srcname`
, `dstname`
, str(why
))
103 def rmtree(path
, ignore_errors
=0, onerror
=None):
104 """Recursively delete a directory tree.
106 If ignore_errors is set, errors are ignored; otherwise, if
107 onerror is set, it is called to handle the error; otherwise, an
112 _build_cmdtuple(path
, cmdtuples
)
113 for cmd
in cmdtuples
:
115 apply(cmd
[0], (cmd
[1],))
121 onerror(cmd
[0], cmd
[1], exc
)
123 raise exc
[0], (exc
[1][0], exc
[1][1] + ' removing '+cmd
[1])
125 # Helper for rmtree()
126 def _build_cmdtuple(path
, cmdtuples
):
127 for f
in os
.listdir(path
):
128 real_f
= os
.path
.join(path
,f
)
129 if os
.path
.isdir(real_f
) and not os
.path
.islink(real_f
):
130 _build_cmdtuple(real_f
, cmdtuples
)
132 cmdtuples
.append((os
.remove
, real_f
))
133 cmdtuples
.append((os
.rmdir
, path
))