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.
11 __all__
= ["copyfileobj","copyfile","copymode","copystat","copy","copy2",
14 def copyfileobj(fsrc
, fdst
, length
=16*1024):
15 """copy data from file-like object fsrc to file-like object fdst"""
17 buf
= fsrc
.read(length
)
23 def copyfile(src
, dst
):
24 """Copy data from src to dst"""
28 fsrc
= open(src
, 'rb')
29 fdst
= open(dst
, 'wb')
30 copyfileobj(fsrc
, fdst
)
37 def copymode(src
, dst
):
38 """Copy mode bits from src to dst"""
39 if hasattr(os
, 'chmod'):
41 mode
= stat
.S_IMODE(st
[stat
.ST_MODE
])
44 def copystat(src
, dst
):
45 """Copy all stat info (mode bits, atime and mtime) from src to dst"""
47 mode
= stat
.S_IMODE(st
[stat
.ST_MODE
])
48 if hasattr(os
, 'utime'):
49 os
.utime(dst
, (st
[stat
.ST_ATIME
], st
[stat
.ST_MTIME
]))
50 if hasattr(os
, 'chmod'):
55 """Copy data and mode bits ("cp src dst").
57 The destination may be a directory.
60 if os
.path
.isdir(dst
):
61 dst
= os
.path
.join(dst
, os
.path
.basename(src
))
66 """Copy data and all stat info ("cp -p src dst").
68 The destination may be a directory.
71 if os
.path
.isdir(dst
):
72 dst
= os
.path
.join(dst
, os
.path
.basename(src
))
77 def copytree(src
, dst
, symlinks
=0):
78 """Recursively copy a directory tree using copy2().
80 The destination directory must not already exist.
81 Error are reported to standard output.
83 If the optional symlinks flag is true, symbolic links in the
84 source tree result in symbolic links in the destination tree; if
85 it is false, the contents of the files pointed to by symbolic
88 XXX Consider this example code rather than the ultimate tool.
91 names
= os
.listdir(src
)
94 srcname
= os
.path
.join(src
, name
)
95 dstname
= os
.path
.join(dst
, name
)
97 if symlinks
and os
.path
.islink(srcname
):
98 linkto
= os
.readlink(srcname
)
99 os
.symlink(linkto
, dstname
)
100 elif os
.path
.isdir(srcname
):
101 copytree(srcname
, dstname
, symlinks
)
103 copy2(srcname
, dstname
)
104 # XXX What about devices, sockets etc.?
105 except (IOError, os
.error
), why
:
106 print "Can't copy %s to %s: %s" % (`srcname`
, `dstname`
, str(why
))
108 def rmtree(path
, ignore_errors
=0, onerror
=None):
109 """Recursively delete a directory tree.
111 If ignore_errors is set, errors are ignored; otherwise, if
112 onerror is set, it is called to handle the error; otherwise, an
117 _build_cmdtuple(path
, cmdtuples
)
118 for cmd
in cmdtuples
:
120 apply(cmd
[0], (cmd
[1],))
126 onerror(cmd
[0], cmd
[1], exc
)
128 raise exc
[0], (exc
[1][0], exc
[1][1] + ' removing '+cmd
[1])
130 # Helper for rmtree()
131 def _build_cmdtuple(path
, cmdtuples
):
132 for f
in os
.listdir(path
):
133 real_f
= os
.path
.join(path
,f
)
134 if os
.path
.isdir(real_f
) and not os
.path
.islink(real_f
):
135 _build_cmdtuple(real_f
, cmdtuples
)
137 cmdtuples
.append((os
.remove
, real_f
))
138 cmdtuples
.append((os
.rmdir
, path
))