1 """Utility functions for copying files.
3 XXX The functions here don't copy the data fork or other metadata on Mac.
11 def copyfile(src
, dst
):
12 """Copy data from src to dst"""
16 fsrc
= open(src
, 'rb')
17 fdst
= open(dst
, 'wb')
19 buf
= fsrc
.read(16*1024)
29 def copymode(src
, dst
):
30 """Copy mode bits from src to dst"""
32 mode
= stat
.S_IMODE(st
[stat
.ST_MODE
])
35 def copystat(src
, dst
):
36 """Copy all stat info (mode bits, atime and mtime) from src to dst"""
38 mode
= stat
.S_IMODE(st
[stat
.ST_MODE
])
40 os
.utime(dst
, (st
[stat
.ST_ATIME
], st
[stat
.ST_MODE
]))
44 """Copy data and mode bits ("cp src dst").
46 The destination may be a directory.
49 if os
.path
.isdir(dst
):
50 dst
= os
.path
.join(dst
, os
.path
.basename(src
))
55 """Copy data and all stat info ("cp -p 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 def copytree(src
, dst
, symlinks
=0):
67 """Recursively copy a directory tree using copy2().
69 The destination directory must not already exist.
70 Error are reported to standard output.
72 If the optional symlinks flag is true, symbolic links in the
73 source tree result in symbolic links in the destination tree; if
74 it is false, the contents of the files pointed to by symbolic
77 XXX Consider this example code rather than the ultimate tool.
80 names
= os
.listdir(src
)
83 srcname
= os
.path
.join(src
, name
)
84 dstname
= os
.path
.join(dst
, name
)
86 if symlinks
and os
.path
.islink(srcname
):
87 linkto
= os
.readlink(srcname
)
88 os
.symlink(linkto
, dstname
)
89 elif os
.path
.isdir(srcname
):
90 copytree(srcname
, dstname
)
92 copy2(srcname
, dstname
)
93 # XXX What about devices, sockets etc.?
94 except (IOError, os
.error
), why
:
95 print "Can't copy %s to %s: %s" % (`srcname`
, `dstname`
, str(why
))
97 def rmtree(path
, ignore_errors
=0, onerror
=None):
98 """Recursively delete a directory tree.
100 If ignore_errors is set, errors are ignored; otherwise, if
101 onerror is set, it is called to handle the error; otherwise, an
106 _build_cmdtuple(path
, cmdtuples
)
107 for cmd
in cmdtuples
:
109 apply(cmd
[0], (cmd
[1],))
115 onerror(cmd
[0], cmd
[1], exc
)
117 raise exc
[0], (exc
[1][0], exc
[1][1] + ' removing '+cmd
[1])
119 # Helper for rmtree()
120 def _build_cmdtuple(path
, cmdtuples
):
121 for f
in os
.listdir(path
):
122 real_f
= os
.path
.join(path
,f
)
123 if os
.path
.isdir(real_f
) and not os
.path
.islink(real_f
):
124 _build_cmdtuple(real_f
, cmdtuples
)
126 cmdtuples
.append(os
.remove
, real_f
)
127 cmdtuples
.append(os
.rmdir
, path
)