blob: 82974ade226170503436583cd50d8038874ab91d [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001:mod:`shutil` --- High-level file operations
2============================================
3
4.. module:: shutil
5 :synopsis: High-level file operations, including copying.
6.. sectionauthor:: Fred L. Drake, Jr. <fdrake@acm.org>
Christian Heimes5b5e81c2007-12-31 16:14:33 +00007.. partly based on the docstrings
Georg Brandl116aa622007-08-15 14:28:22 +00008
9.. index::
10 single: file; copying
11 single: copying files
12
Raymond Hettinger10480942011-01-10 03:26:08 +000013**Source code:** :source:`Lib/shutil.py`
14
Raymond Hettinger4f707fd2011-01-10 19:54:11 +000015--------------
16
Georg Brandl116aa622007-08-15 14:28:22 +000017The :mod:`shutil` module offers a number of high-level operations on files and
18collections of files. In particular, functions are provided which support file
Guido van Rossum2cc30da2007-11-02 23:46:40 +000019copying and removal. For operations on individual files, see also the
20:mod:`os` module.
Georg Brandl116aa622007-08-15 14:28:22 +000021
Guido van Rossumda27fd22007-08-17 00:24:54 +000022.. warning::
Christian Heimes7f044312008-01-06 17:05:40 +000023
Senthil Kumaran7f728c12012-02-13 23:30:47 +080024 Even the higher-level file copying functions (:func:`shutil.copy`,
25 :func:`shutil.copy2`) cannot copy all file metadata.
Georg Brandl48310cd2009-01-03 21:18:54 +000026
Christian Heimes7f044312008-01-06 17:05:40 +000027 On POSIX platforms, this means that file owner and group are lost as well
Georg Brandlc575c902008-09-13 17:46:05 +000028 as ACLs. On Mac OS, the resource fork and other metadata are not used.
Christian Heimes7f044312008-01-06 17:05:40 +000029 This means that resources will be lost and file type and creator codes will
30 not be correct. On Windows, file owners, ACLs and alternate data streams
31 are not copied.
Georg Brandl116aa622007-08-15 14:28:22 +000032
Éric Araujo6e6cb8e2010-11-16 19:13:50 +000033
Éric Araujof2fbb9c2012-01-16 16:55:55 +010034.. _file-operations:
35
Tarek Ziadé396fad72010-02-23 05:30:31 +000036Directory and files operations
37------------------------------
Georg Brandl116aa622007-08-15 14:28:22 +000038
Georg Brandl116aa622007-08-15 14:28:22 +000039.. function:: copyfileobj(fsrc, fdst[, length])
40
41 Copy the contents of the file-like object *fsrc* to the file-like object *fdst*.
42 The integer *length*, if given, is the buffer size. In particular, a negative
43 *length* value means to copy the data without looping over the source data in
44 chunks; by default the data is read in chunks to avoid uncontrolled memory
45 consumption. Note that if the current file position of the *fsrc* object is not
46 0, only the contents from the current file position to the end of the file will
47 be copied.
48
49
Larry Hastingsb4038062012-07-15 10:57:38 -070050.. function:: copyfile(src, dst, *, follow_symlinks=True)
Christian Heimesa342c012008-04-20 21:01:16 +000051
Senthil Kumaran7f728c12012-02-13 23:30:47 +080052 Copy the contents (no metadata) of the file named *src* to a file named
Larry Hastings60eba572012-09-21 10:12:14 -070053 *dst* and return *dst*. *src* and *dst* are path names given as strings.
54 *dst* must be the complete target file name; look at :func:`shutil.copy`
55 for a copy that accepts a target directory path. If *src* and *dst*
Hynek Schlawack48653762012-10-07 12:49:58 +020056 specify the same file, :exc:`SameFileError` is raised.
Senthil Kumaran1fd64822012-02-13 23:35:44 +080057
Larry Hastings60eba572012-09-21 10:12:14 -070058 The destination location must be writable; otherwise, an :exc:`OSError`
59 exception will be raised. If *dst* already exists, it will be replaced.
60 Special files such as character or block devices and pipes cannot be
61 copied with this function.
Christian Heimesa342c012008-04-20 21:01:16 +000062
Larry Hastings7aa2c8b2012-07-15 16:58:29 -070063 If *follow_symlinks* is false and *src* is a symbolic link,
64 a new symbolic link will be created instead of copying the
65 file *src* points to.
Antoine Pitrou78091e62011-12-29 18:54:15 +010066
Antoine Pitrou62ab10a02011-10-12 20:10:51 +020067 .. versionchanged:: 3.3
68 :exc:`IOError` used to be raised instead of :exc:`OSError`.
Larry Hastings7aa2c8b2012-07-15 16:58:29 -070069 Added *follow_symlinks* argument.
70 Now returns *dst*.
Antoine Pitrou62ab10a02011-10-12 20:10:51 +020071
Hynek Schlawack48653762012-10-07 12:49:58 +020072 .. versionchanged:: 3.4
Hynek Schlawack27ddb572012-10-28 13:59:27 +010073 Raise :exc:`SameFileError` instead of :exc:`Error`. Since the former is
74 a subclass of the latter, this change is backward compatible.
Hynek Schlawack48653762012-10-07 12:49:58 +020075
76
77.. exception:: SameFileError
78
79 This exception is raised if source and destination in :func:`copyfile`
80 are the same file.
81
82 .. versionadded:: 3.4
83
84
Larry Hastings7aa2c8b2012-07-15 16:58:29 -070085.. function:: copymode(src, dst, *, follow_symlinks=True)
Georg Brandl116aa622007-08-15 14:28:22 +000086
87 Copy the permission bits from *src* to *dst*. The file contents, owner, and
Larry Hastings60eba572012-09-21 10:12:14 -070088 group are unaffected. *src* and *dst* are path names given as strings.
89 If *follow_symlinks* is false, and both *src* and *dst* are symbolic links,
90 :func:`copymode` will attempt to modify the mode of *dst* itself (rather
91 than the file it points to). This functionality is not available on every
92 platform; please see :func:`copystat` for more information. If
93 :func:`copymode` cannot modify symbolic links on the local platform, and it
94 is asked to do so, it will do nothing and return.
Georg Brandl116aa622007-08-15 14:28:22 +000095
Antoine Pitrou78091e62011-12-29 18:54:15 +010096 .. versionchanged:: 3.3
Larry Hastings7aa2c8b2012-07-15 16:58:29 -070097 Added *follow_symlinks* argument.
Georg Brandl116aa622007-08-15 14:28:22 +000098
Larry Hastings7aa2c8b2012-07-15 16:58:29 -070099.. function:: copystat(src, dst, *, follow_symlinks=True)
Georg Brandl116aa622007-08-15 14:28:22 +0000100
Larry Hastings60eba572012-09-21 10:12:14 -0700101 Copy the permission bits, last access time, last modification time, and
102 flags from *src* to *dst*. On Linux, :func:`copystat` also copies the
103 "extended attributes" where possible. The file contents, owner, and
104 group are unaffected. *src* and *dst* are path names given as strings.
105
106 If *follow_symlinks* is false, and *src* and *dst* both
107 refer to symbolic links, :func:`copystat` will operate on
108 the symbolic links themselves rather than the files the
109 symbolic links refer to--reading the information from the
110 *src* symbolic link, and writing the information to the
111 *dst* symbolic link.
112
113 .. note::
114
115 Not all platforms provide the ability to examine and
116 modify symbolic links. Python itself can tell you what
117 functionality is locally available.
118
119 * If ``os.chmod in os.supports_follow_symlinks`` is
120 ``True``, :func:`copystat` can modify the permission
121 bits of a symbolic link.
122
123 * If ``os.utime in os.supports_follow_symlinks`` is
124 ``True``, :func:`copystat` can modify the last access
125 and modification times of a symbolic link.
126
127 * If ``os.chflags in os.supports_follow_symlinks`` is
128 ``True``, :func:`copystat` can modify the flags of
129 a symbolic link. (``os.chflags`` is not available on
130 all platforms.)
131
132 On platforms where some or all of this functionality
133 is unavailable, when asked to modify a symbolic link,
134 :func:`copystat` will copy everything it can.
135 :func:`copystat` never returns failure.
136
137 Please see :data:`os.supports_follow_symlinks`
138 for more information.
Georg Brandl116aa622007-08-15 14:28:22 +0000139
Antoine Pitrou78091e62011-12-29 18:54:15 +0100140 .. versionchanged:: 3.3
Larry Hastings7aa2c8b2012-07-15 16:58:29 -0700141 Added *follow_symlinks* argument and support for Linux extended attributes.
Georg Brandl116aa622007-08-15 14:28:22 +0000142
Larry Hastings7aa2c8b2012-07-15 16:58:29 -0700143.. function:: copy(src, dst, *, follow_symlinks=True)
Georg Brandl116aa622007-08-15 14:28:22 +0000144
Larry Hastings60eba572012-09-21 10:12:14 -0700145 Copies the file *src* to the file or directory *dst*. *src* and *dst*
146 should be strings. If *dst* specifies a directory, the file will be
147 copied into *dst* using the base filename from *src*. Returns the
148 path to the newly created file.
149
150 If *follow_symlinks* is false, and *src* is a symbolic link,
151 *dst* will be created as a symbolic link. If *follow_symlinks*
152 is true and *src* is a symbolic link, *dst* will be a copy of
153 the file *src* refers to.
154
155 :func:`copy` copies the file data and the file's permission
156 mode (see :func:`os.chmod`). Other metadata, like the
157 file's creation and modification times, is not preserved.
158 To preserve all file metadata from the original, use
159 :func:`~shutil.copy2` instead.
Georg Brandl116aa622007-08-15 14:28:22 +0000160
Antoine Pitrou78091e62011-12-29 18:54:15 +0100161 .. versionchanged:: 3.3
Larry Hastings7aa2c8b2012-07-15 16:58:29 -0700162 Added *follow_symlinks* argument.
Larry Hastings60eba572012-09-21 10:12:14 -0700163 Now returns path to the newly created file.
Georg Brandl116aa622007-08-15 14:28:22 +0000164
Larry Hastings7aa2c8b2012-07-15 16:58:29 -0700165.. function:: copy2(src, dst, *, follow_symlinks=True)
Georg Brandl116aa622007-08-15 14:28:22 +0000166
Larry Hastings60eba572012-09-21 10:12:14 -0700167 Identical to :func:`~shutil.copy` except that :func:`copy2`
168 also attempts to preserve all file metadata.
169
170 When *follow_symlinks* is false, and *src* is a symbolic
171 link, :func:`copy2` attempts to copy all metadata from the
172 *src* symbolic link to the newly-created *dst* symbolic link.
173 However, this functionality is not available on all platforms.
174 On platforms where some or all of this functionality is
175 unavailable, :func:`copy2` will preserve all the metadata
176 it can; :func:`copy2` never returns failure.
177
178 :func:`copy2` uses :func:`copystat` to copy the file metadata.
179 Please see :func:`copystat` for more information
180 about platform support for modifying symbolic link metadata.
Georg Brandl116aa622007-08-15 14:28:22 +0000181
Antoine Pitrou78091e62011-12-29 18:54:15 +0100182 .. versionchanged:: 3.3
Larry Hastings7aa2c8b2012-07-15 16:58:29 -0700183 Added *follow_symlinks* argument, try to copy extended
184 file system attributes too (currently Linux only).
Larry Hastings60eba572012-09-21 10:12:14 -0700185 Now returns path to the newly created file.
Brian Curtin066dacf2012-06-19 10:03:05 -0500186
Georg Brandl86b2fb92008-07-16 03:43:04 +0000187.. function:: ignore_patterns(\*patterns)
188
189 This factory function creates a function that can be used as a callable for
190 :func:`copytree`\'s *ignore* argument, ignoring files and directories that
191 match one of the glob-style *patterns* provided. See the example below.
192
193
R David Murray6ffface2014-06-11 14:40:13 -0400194.. function:: copytree(src, dst, symlinks=False, ignore=None, \
195 copy_function=copy2, ignore_dangling_symlinks=False)
Georg Brandl116aa622007-08-15 14:28:22 +0000196
Brian Curtin0d0a1de2012-06-18 18:41:07 -0500197 Recursively copy an entire directory tree rooted at *src*, returning the
198 destination directory. The destination
Senthil Kumaran7f728c12012-02-13 23:30:47 +0800199 directory, named by *dst*, must not already exist; it will be created as
200 well as missing parent directories. Permissions and times of directories
201 are copied with :func:`copystat`, individual files are copied using
202 :func:`shutil.copy2`.
Georg Brandl116aa622007-08-15 14:28:22 +0000203
Georg Brandl86b2fb92008-07-16 03:43:04 +0000204 If *symlinks* is true, symbolic links in the source tree are represented as
Antoine Pitrou78091e62011-12-29 18:54:15 +0100205 symbolic links in the new tree and the metadata of the original links will
206 be copied as far as the platform allows; if false or omitted, the contents
207 and metadata of the linked files are copied to the new tree.
Georg Brandl86b2fb92008-07-16 03:43:04 +0000208
Tarek Ziadéfb437512010-04-20 08:57:33 +0000209 When *symlinks* is false, if the file pointed by the symlink doesn't
210 exist, a exception will be added in the list of errors raised in
211 a :exc:`Error` exception at the end of the copy process.
212 You can set the optional *ignore_dangling_symlinks* flag to true if you
Tarek Ziadé8c26c7d2010-04-23 13:03:50 +0000213 want to silence this exception. Notice that this option has no effect
214 on platforms that don't support :func:`os.symlink`.
Tarek Ziadéfb437512010-04-20 08:57:33 +0000215
Georg Brandl86b2fb92008-07-16 03:43:04 +0000216 If *ignore* is given, it must be a callable that will receive as its
217 arguments the directory being visited by :func:`copytree`, and a list of its
218 contents, as returned by :func:`os.listdir`. Since :func:`copytree` is
219 called recursively, the *ignore* callable will be called once for each
220 directory that is copied. The callable must return a sequence of directory
221 and file names relative to the current directory (i.e. a subset of the items
222 in its second argument); these names will then be ignored in the copy
223 process. :func:`ignore_patterns` can be used to create such a callable that
224 ignores names based on glob-style patterns.
225
226 If exception(s) occur, an :exc:`Error` is raised with a list of reasons.
227
Senthil Kumaran7f728c12012-02-13 23:30:47 +0800228 If *copy_function* is given, it must be a callable that will be used to copy
229 each file. It will be called with the source path and the destination path
230 as arguments. By default, :func:`shutil.copy2` is used, but any function
Senthil Kumaran1fd64822012-02-13 23:35:44 +0800231 that supports the same signature (like :func:`shutil.copy`) can be used.
Georg Brandl116aa622007-08-15 14:28:22 +0000232
Larry Hastings7aa2c8b2012-07-15 16:58:29 -0700233 .. versionchanged:: 3.3
234 Copy metadata when *symlinks* is false.
235 Now returns *dst*.
236
Tarek Ziadé5340db32010-04-19 22:30:51 +0000237 .. versionchanged:: 3.2
238 Added the *copy_function* argument to be able to provide a custom copy
239 function.
Tarek Ziadéfb437512010-04-20 08:57:33 +0000240 Added the *ignore_dangling_symlinks* argument to silent dangling symlinks
241 errors when *symlinks* is false.
242
Georg Brandl96acb732012-06-24 17:39:05 +0200243
Georg Brandl18244152009-09-02 20:34:52 +0000244.. function:: rmtree(path, ignore_errors=False, onerror=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000245
246 .. index:: single: directory; deleting
247
Christian Heimes9bd667a2008-01-20 15:14:11 +0000248 Delete an entire directory tree; *path* must point to a directory (but not a
249 symbolic link to a directory). If *ignore_errors* is true, errors resulting
250 from failed removals will be ignored; if false or omitted, such errors are
251 handled by calling a handler specified by *onerror* or, if that is omitted,
252 they raise an exception.
Georg Brandl116aa622007-08-15 14:28:22 +0000253
Nick Coghlan5b0eca12012-06-24 16:43:06 +1000254 .. note::
Hynek Schlawack67be92b2012-06-23 17:58:42 +0200255
Nick Coghlan5b0eca12012-06-24 16:43:06 +1000256 On platforms that support the necessary fd-based functions a symlink
Georg Brandl96acb732012-06-24 17:39:05 +0200257 attack resistant version of :func:`rmtree` is used by default. On other
258 platforms, the :func:`rmtree` implementation is susceptible to a symlink
259 attack: given proper timing and circumstances, attackers can manipulate
260 symlinks on the filesystem to delete files they wouldn't be able to access
261 otherwise. Applications can use the :data:`rmtree.avoids_symlink_attacks`
262 function attribute to determine which case applies.
Hynek Schlawack67be92b2012-06-23 17:58:42 +0200263
Christian Heimes9bd667a2008-01-20 15:14:11 +0000264 If *onerror* is provided, it must be a callable that accepts three
Hynek Schlawack67be92b2012-06-23 17:58:42 +0200265 parameters: *function*, *path*, and *excinfo*.
266
267 The first parameter, *function*, is the function which raised the exception;
268 it depends on the platform and implementation. The second parameter,
269 *path*, will be the path name passed to *function*. The third parameter,
270 *excinfo*, will be the exception information returned by
271 :func:`sys.exc_info`. Exceptions raised by *onerror* will not be caught.
272
273 .. versionchanged:: 3.3
Nick Coghlan5b0eca12012-06-24 16:43:06 +1000274 Added a symlink attack resistant version that is used automatically
275 if platform supports fd-based functions.
Christian Heimes9bd667a2008-01-20 15:14:11 +0000276
Éric Araujo544e13d2012-06-24 13:53:48 -0400277 .. attribute:: rmtree.avoids_symlink_attacks
Hynek Schlawack2100b422012-06-23 20:28:32 +0200278
Nick Coghlan5b0eca12012-06-24 16:43:06 +1000279 Indicates whether the current platform and implementation provides a
Georg Brandl96acb732012-06-24 17:39:05 +0200280 symlink attack resistant version of :func:`rmtree`. Currently this is
Nick Coghlan5b0eca12012-06-24 16:43:06 +1000281 only true for platforms supporting fd-based directory access functions.
Hynek Schlawack2100b422012-06-23 20:28:32 +0200282
Nick Coghlan5b0eca12012-06-24 16:43:06 +1000283 .. versionadded:: 3.3
Georg Brandl116aa622007-08-15 14:28:22 +0000284
Georg Brandl96acb732012-06-24 17:39:05 +0200285
R David Murray6ffface2014-06-11 14:40:13 -0400286.. function:: move(src, dst, copy_function=copy2)
Georg Brandl116aa622007-08-15 14:28:22 +0000287
Brian Curtin0d0a1de2012-06-18 18:41:07 -0500288 Recursively move a file or directory (*src*) to another location (*dst*)
289 and return the destination.
Georg Brandl116aa622007-08-15 14:28:22 +0000290
Éric Araujo14382dc2011-07-28 22:49:11 +0200291 If the destination is a directory or a symlink to a directory, then *src* is
292 moved inside that directory.
293
294 The destination directory must not already exist. If the destination already
295 exists but is not a directory, it may be overwritten depending on
296 :func:`os.rename` semantics.
297
298 If the destination is on the current filesystem, then :func:`os.rename` is
R David Murray6ffface2014-06-11 14:40:13 -0400299 used. Otherwise, *src* is copied to *dst* using *copy_function* and then
300 removed. In case of symlinks, a new symlink pointing to the target of *src*
301 will be created in or as *dst* and *src* will be removed.
302
303 If *copy_function* is given, it must be a callable that takes two arguments
304 *src* and *dst*, and will be used to copy *src* to *dest* if
305 :func:`os.rename` cannot be used. If the source is a directory,
306 :func:`copytree` is called, passing it the :func:`copy_function`. The
307 default *copy_function* is :func:`copy2`. Using :func:`copy` as the
308 *copy_function* allows the move to succeed when it is not possible to also
309 copy the metadata, at the expense of not copying any of the metadata.
Antoine Pitrou0a08d7a2012-01-06 20:16:19 +0100310
311 .. versionchanged:: 3.3
312 Added explicit symlink handling for foreign filesystems, thus adapting
313 it to the behavior of GNU's :program:`mv`.
Larry Hastings7aa2c8b2012-07-15 16:58:29 -0700314 Now returns *dst*.
Brian Curtin066dacf2012-06-19 10:03:05 -0500315
R David Murray6ffface2014-06-11 14:40:13 -0400316 .. versionchanged:: 3.5
317 Added the *copy_function* keyword argument.
318
Giampaolo Rodola'210e7ca2011-07-01 13:55:36 +0200319.. function:: disk_usage(path)
320
Éric Araujoe4d5b8e2011-08-08 16:51:11 +0200321 Return disk usage statistics about the given path as a :term:`named tuple`
322 with the attributes *total*, *used* and *free*, which are the amount of
323 total, used and free space, in bytes.
Giampaolo Rodola'210e7ca2011-07-01 13:55:36 +0200324
325 .. versionadded:: 3.3
326
327 Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000328
Sandro Tosid902a142011-08-22 23:28:27 +0200329.. function:: chown(path, user=None, group=None)
330
331 Change owner *user* and/or *group* of the given *path*.
332
333 *user* can be a system user name or a uid; the same applies to *group*. At
334 least one argument is required.
335
336 See also :func:`os.chown`, the underlying function.
337
338 Availability: Unix.
339
340 .. versionadded:: 3.3
341
Georg Brandl4a7e25f2012-06-24 17:37:07 +0200342
Brian Curtinc57a3452012-06-22 16:00:30 -0500343.. function:: which(cmd, mode=os.F_OK | os.X_OK, path=None)
344
Georg Brandl4a7e25f2012-06-24 17:37:07 +0200345 Return the path to an executable which would be run if the given *cmd* was
346 called. If no *cmd* would be called, return ``None``.
Brian Curtinc57a3452012-06-22 16:00:30 -0500347
348 *mode* is a permission mask passed a to :func:`os.access`, by default
349 determining if the file exists and executable.
350
Georg Brandl4a7e25f2012-06-24 17:37:07 +0200351 When no *path* is specified, the results of :func:`os.environ` are used,
352 returning either the "PATH" value or a fallback of :attr:`os.defpath`.
Brian Curtinc57a3452012-06-22 16:00:30 -0500353
Georg Brandl4a7e25f2012-06-24 17:37:07 +0200354 On Windows, the current directory is always prepended to the *path* whether
355 or not you use the default or provide your own, which is the behavior the
Donald Stufft8b852f12014-05-20 12:58:38 -0400356 command shell uses when finding executables. Additionally, when finding the
Georg Brandl4a7e25f2012-06-24 17:37:07 +0200357 *cmd* in the *path*, the ``PATHEXT`` environment variable is checked. For
358 example, if you call ``shutil.which("python")``, :func:`which` will search
359 ``PATHEXT`` to know that it should look for ``python.exe`` within the *path*
360 directories. For example, on Windows::
Brian Curtinc57a3452012-06-22 16:00:30 -0500361
Georg Brandl4a7e25f2012-06-24 17:37:07 +0200362 >>> shutil.which("python")
Serhiy Storchaka80c88f42013-01-22 10:31:36 +0200363 'C:\\Python33\\python.EXE'
Brian Curtinc57a3452012-06-22 16:00:30 -0500364
365 .. versionadded:: 3.3
Sandro Tosid902a142011-08-22 23:28:27 +0200366
Georg Brandl4a7e25f2012-06-24 17:37:07 +0200367
Georg Brandl116aa622007-08-15 14:28:22 +0000368.. exception:: Error
369
Éric Araujo14382dc2011-07-28 22:49:11 +0200370 This exception collects exceptions that are raised during a multi-file
371 operation. For :func:`copytree`, the exception argument is a list of 3-tuples
372 (*srcname*, *dstname*, *exception*).
Georg Brandl116aa622007-08-15 14:28:22 +0000373
Georg Brandl116aa622007-08-15 14:28:22 +0000374
Éric Araujof2fbb9c2012-01-16 16:55:55 +0100375.. _shutil-copytree-example:
Georg Brandl116aa622007-08-15 14:28:22 +0000376
Tarek Ziadé396fad72010-02-23 05:30:31 +0000377copytree example
Georg Brandl03b9ad02012-06-24 18:09:40 +0200378~~~~~~~~~~~~~~~~
Georg Brandl116aa622007-08-15 14:28:22 +0000379
380This example is the implementation of the :func:`copytree` function, described
381above, with the docstring omitted. It demonstrates many of the other functions
382provided by this module. ::
383
384 def copytree(src, dst, symlinks=False):
385 names = os.listdir(src)
386 os.makedirs(dst)
387 errors = []
388 for name in names:
389 srcname = os.path.join(src, name)
390 dstname = os.path.join(dst, name)
391 try:
392 if symlinks and os.path.islink(srcname):
393 linkto = os.readlink(srcname)
394 os.symlink(linkto, dstname)
395 elif os.path.isdir(srcname):
396 copytree(srcname, dstname, symlinks)
397 else:
398 copy2(srcname, dstname)
399 # XXX What about devices, sockets etc.?
Andrew Svetlov618c2e12012-12-15 22:59:24 +0200400 except OSError as why:
Georg Brandl116aa622007-08-15 14:28:22 +0000401 errors.append((srcname, dstname, str(why)))
402 # catch the Error from the recursive copytree so that we can
403 # continue with other files
404 except Error as err:
405 errors.extend(err.args[0])
406 try:
407 copystat(src, dst)
Georg Brandl116aa622007-08-15 14:28:22 +0000408 except OSError as why:
Andrew Svetlov2606a6f2012-12-19 14:33:35 +0200409 # can't copy file access times on Windows
410 if why.winerror is None:
411 errors.extend((src, dst, str(why)))
Georg Brandl116aa622007-08-15 14:28:22 +0000412 if errors:
Collin Winterc79461b2007-09-01 23:34:30 +0000413 raise Error(errors)
Georg Brandl116aa622007-08-15 14:28:22 +0000414
Tarek Ziadé396fad72010-02-23 05:30:31 +0000415Another example that uses the :func:`ignore_patterns` helper::
416
417 from shutil import copytree, ignore_patterns
418
419 copytree(source, destination, ignore=ignore_patterns('*.pyc', 'tmp*'))
420
421This will copy everything except ``.pyc`` files and files or directories whose
422name starts with ``tmp``.
423
424Another example that uses the *ignore* argument to add a logging call::
425
426 from shutil import copytree
427 import logging
428
429 def _logpath(path, names):
430 logging.info('Working in %s' % path)
431 return [] # nothing will be ignored
432
433 copytree(source, destination, ignore=_logpath)
434
435
Tim Golden78337792014-05-07 18:05:45 +0100436.. _shutil-rmtree-example:
437
438rmtree example
439~~~~~~~~~~~~~~
440
441This example shows how to remove a directory tree on Windows where some
442of the files have their read-only bit set. It uses the onerror callback
443to clear the readonly bit and reattempt the remove. Any subsequent failure
444will propagate. ::
445
446 import os, stat
447 import shutil
Tim Goldenba748852014-05-07 18:08:08 +0100448
Tim Golden78337792014-05-07 18:05:45 +0100449 def remove_readonly(func, path, _):
450 "Clear the readonly bit and reattempt the removal"
451 os.chmod(path, stat.S_IWRITE)
Tim Goldenba748852014-05-07 18:08:08 +0100452 func(path)
453
Tim Golden78337792014-05-07 18:05:45 +0100454 shutil.rmtree(directory, onerror=remove_readonly)
455
Raymond Hettinger0929b1f2011-01-23 11:29:08 +0000456.. _archiving-operations:
457
458Archiving operations
459--------------------
Tarek Ziadé396fad72010-02-23 05:30:31 +0000460
Georg Brandl03b9ad02012-06-24 18:09:40 +0200461.. versionadded:: 3.2
462
Éric Araujof2fbb9c2012-01-16 16:55:55 +0100463High-level utilities to create and read compressed and archived files are also
464provided. They rely on the :mod:`zipfile` and :mod:`tarfile` modules.
465
Tarek Ziadé396fad72010-02-23 05:30:31 +0000466.. function:: make_archive(base_name, format, [root_dir, [base_dir, [verbose, [dry_run, [owner, [group, [logger]]]]]]])
467
Raymond Hettinger0929b1f2011-01-23 11:29:08 +0000468 Create an archive file (such as zip or tar) and return its name.
Tarek Ziadé396fad72010-02-23 05:30:31 +0000469
470 *base_name* is the name of the file to create, including the path, minus
471 any format-specific extension. *format* is the archive format: one of
Serhiy Storchaka11213772014-08-06 18:50:19 +0300472 "zip", "tar", "bztar" (if the :mod:`bz2` module is available), "xztar"
473 (if the :mod:`lzma` module is available) or "gztar".
Tarek Ziadé396fad72010-02-23 05:30:31 +0000474
475 *root_dir* is a directory that will be the root directory of the
Raymond Hettinger0929b1f2011-01-23 11:29:08 +0000476 archive; for example, we typically chdir into *root_dir* before creating the
Tarek Ziadé396fad72010-02-23 05:30:31 +0000477 archive.
478
479 *base_dir* is the directory where we start archiving from;
Ezio Melotticb999a32010-04-20 11:26:51 +0000480 i.e. *base_dir* will be the common prefix of all files and
Tarek Ziadé396fad72010-02-23 05:30:31 +0000481 directories in the archive.
482
483 *root_dir* and *base_dir* both default to the current directory.
484
Georg Brandl9b1b0e52014-10-31 10:02:40 +0100485 If *dry_run* is true, no archive is created, but the operations that would be
486 executed are logged to *logger*.
487
Tarek Ziadé396fad72010-02-23 05:30:31 +0000488 *owner* and *group* are used when creating a tar archive. By default,
489 uses the current owner and group.
490
Éric Araujo06c42a32011-11-07 17:31:07 +0100491 *logger* must be an object compatible with :pep:`282`, usually an instance of
492 :class:`logging.Logger`.
Raymond Hettinger0929b1f2011-01-23 11:29:08 +0000493
Georg Brandl36ac5102014-10-31 10:54:06 +0100494 The *verbose* argument is unused and deprecated.
Georg Brandl9b1b0e52014-10-31 10:02:40 +0100495
Serhiy Storchakaf3440c62014-08-06 18:55:54 +0300496 .. versionchanged:: 3.5
Berker Peksagae04ba12014-08-11 18:10:25 +0300497 Added support for the *xztar* format.
Serhiy Storchaka11213772014-08-06 18:50:19 +0300498
Tarek Ziadé396fad72010-02-23 05:30:31 +0000499
500.. function:: get_archive_formats()
501
Éric Araujo14382dc2011-07-28 22:49:11 +0200502 Return a list of supported formats for archiving.
Tarek Ziadé396fad72010-02-23 05:30:31 +0000503 Each element of the returned sequence is a tuple ``(name, description)``
504
505 By default :mod:`shutil` provides these formats:
506
507 - *gztar*: gzip'ed tar-file
Tarek Ziadéffa155a2010-04-29 13:34:35 +0000508 - *bztar*: bzip2'ed tar-file (if the :mod:`bz2` module is available.)
Serhiy Storchaka11213772014-08-06 18:50:19 +0300509 - *xztar*: xz'ed tar-file (if the :mod:`lzma` module is available.)
Tarek Ziadé396fad72010-02-23 05:30:31 +0000510 - *tar*: uncompressed tar file
511 - *zip*: ZIP file
512
513 You can register new formats or provide your own archiver for any existing
514 formats, by using :func:`register_archive_format`.
515
Tarek Ziadé396fad72010-02-23 05:30:31 +0000516
517.. function:: register_archive_format(name, function, [extra_args, [description]])
518
Georg Brandl9b1b0e52014-10-31 10:02:40 +0100519 Register an archiver for the format *name*.
520
521 *function* is the callable that will be used to unpack archives. The callable
522 will receive the *base_name* of the file to create, followed by the
523 *base_dir* (which defaults to :data:`os.curdir`) to start archiving from.
524 Further arguments are passed as keyword arguments: *owner*, *group*,
525 *dry_run* and *logger* (as passed in :func:`make_archive`).
Tarek Ziadé396fad72010-02-23 05:30:31 +0000526
Raymond Hettinger0929b1f2011-01-23 11:29:08 +0000527 If given, *extra_args* is a sequence of ``(name, value)`` pairs that will be
Tarek Ziadé396fad72010-02-23 05:30:31 +0000528 used as extra keywords arguments when the archiver callable is used.
529
530 *description* is used by :func:`get_archive_formats` which returns the
Georg Brandl9b1b0e52014-10-31 10:02:40 +0100531 list of archivers. Defaults to an empty string.
Tarek Ziadé396fad72010-02-23 05:30:31 +0000532
Tarek Ziadé396fad72010-02-23 05:30:31 +0000533
Tarek Ziadé6ac91722010-04-28 17:51:36 +0000534.. function:: unregister_archive_format(name)
Tarek Ziadé396fad72010-02-23 05:30:31 +0000535
536 Remove the archive format *name* from the list of supported formats.
537
Tarek Ziadé396fad72010-02-23 05:30:31 +0000538
Tarek Ziadé6ac91722010-04-28 17:51:36 +0000539.. function:: unpack_archive(filename[, extract_dir[, format]])
540
541 Unpack an archive. *filename* is the full path of the archive.
542
543 *extract_dir* is the name of the target directory where the archive is
544 unpacked. If not provided, the current working directory is used.
545
546 *format* is the archive format: one of "zip", "tar", or "gztar". Or any
547 other format registered with :func:`register_unpack_format`. If not
548 provided, :func:`unpack_archive` will use the archive file name extension
549 and see if an unpacker was registered for that extension. In case none is
550 found, a :exc:`ValueError` is raised.
551
Tarek Ziadé6ac91722010-04-28 17:51:36 +0000552
Raymond Hettinger0929b1f2011-01-23 11:29:08 +0000553.. function:: register_unpack_format(name, extensions, function[, extra_args[, description]])
Tarek Ziadé6ac91722010-04-28 17:51:36 +0000554
555 Registers an unpack format. *name* is the name of the format and
556 *extensions* is a list of extensions corresponding to the format, like
557 ``.zip`` for Zip files.
558
559 *function* is the callable that will be used to unpack archives. The
560 callable will receive the path of the archive, followed by the directory
561 the archive must be extracted to.
562
563 When provided, *extra_args* is a sequence of ``(name, value)`` tuples that
564 will be passed as keywords arguments to the callable.
565
566 *description* can be provided to describe the format, and will be returned
567 by the :func:`get_unpack_formats` function.
568
Tarek Ziadé6ac91722010-04-28 17:51:36 +0000569
570.. function:: unregister_unpack_format(name)
571
572 Unregister an unpack format. *name* is the name of the format.
573
Tarek Ziadé6ac91722010-04-28 17:51:36 +0000574
575.. function:: get_unpack_formats()
576
577 Return a list of all registered formats for unpacking.
578 Each element of the returned sequence is a tuple
579 ``(name, extensions, description)``.
580
581 By default :mod:`shutil` provides these formats:
582
583 - *gztar*: gzip'ed tar-file
Tarek Ziadéffa155a2010-04-29 13:34:35 +0000584 - *bztar*: bzip2'ed tar-file (if the :mod:`bz2` module is available.)
Serhiy Storchaka11213772014-08-06 18:50:19 +0300585 - *xztar*: xz'ed tar-file (if the :mod:`lzma` module is available.)
Tarek Ziadé6ac91722010-04-28 17:51:36 +0000586 - *tar*: uncompressed tar file
587 - *zip*: ZIP file
588
589 You can register new formats or provide your own unpacker for any existing
590 formats, by using :func:`register_unpack_format`.
591
Tarek Ziadé6ac91722010-04-28 17:51:36 +0000592
Éric Araujof2fbb9c2012-01-16 16:55:55 +0100593.. _shutil-archiving-example:
Tarek Ziadé6ac91722010-04-28 17:51:36 +0000594
Tarek Ziadé396fad72010-02-23 05:30:31 +0000595Archiving example
Georg Brandl03b9ad02012-06-24 18:09:40 +0200596~~~~~~~~~~~~~~~~~
Tarek Ziadé396fad72010-02-23 05:30:31 +0000597
598In this example, we create a gzip'ed tar-file archive containing all files
599found in the :file:`.ssh` directory of the user::
600
601 >>> from shutil import make_archive
602 >>> import os
603 >>> archive_name = os.path.expanduser(os.path.join('~', 'myarchive'))
604 >>> root_dir = os.path.expanduser(os.path.join('~', '.ssh'))
605 >>> make_archive(archive_name, 'gztar', root_dir)
606 '/Users/tarek/myarchive.tar.gz'
607
608The resulting archive contains::
609
610 $ tar -tzvf /Users/tarek/myarchive.tar.gz
611 drwx------ tarek/staff 0 2010-02-01 16:23:40 ./
612 -rw-r--r-- tarek/staff 609 2008-06-09 13:26:54 ./authorized_keys
613 -rwxr-xr-x tarek/staff 65 2008-06-09 13:26:54 ./config
614 -rwx------ tarek/staff 668 2008-06-09 13:26:54 ./id_dsa
615 -rwxr-xr-x tarek/staff 609 2008-06-09 13:26:54 ./id_dsa.pub
616 -rw------- tarek/staff 1675 2008-06-09 13:26:54 ./id_rsa
617 -rw-r--r-- tarek/staff 397 2008-06-09 13:26:54 ./id_rsa.pub
618 -rw-r--r-- tarek/staff 37192 2010-02-06 18:23:10 ./known_hosts
Antoine Pitroubcf2b592012-02-08 23:28:36 +0100619
620
621Querying the size of the output terminal
622----------------------------------------
623
624.. versionadded:: 3.3
625
626.. function:: get_terminal_size(fallback=(columns, lines))
627
628 Get the size of the terminal window.
629
630 For each of the two dimensions, the environment variable, ``COLUMNS``
631 and ``LINES`` respectively, is checked. If the variable is defined and
632 the value is a positive integer, it is used.
633
634 When ``COLUMNS`` or ``LINES`` is not defined, which is the common case,
635 the terminal connected to :data:`sys.__stdout__` is queried
636 by invoking :func:`os.get_terminal_size`.
637
638 If the terminal size cannot be successfully queried, either because
639 the system doesn't support querying, or because we are not
640 connected to a terminal, the value given in ``fallback`` parameter
641 is used. ``fallback`` defaults to ``(80, 24)`` which is the default
642 size used by many terminal emulators.
643
644 The value returned is a named tuple of type :class:`os.terminal_size`.
645
646 See also: The Single UNIX Specification, Version 2,
647 `Other Environment Variables`_.
648
649.. _`Other Environment Variables`:
650 http://pubs.opengroup.org/onlinepubs/7908799/xbd/envvar.html#tag_002_003
651