blob: ec8cad25f213155003e04cb4c09ddccf11d52ace [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
73 Raise :exc:`SameFileError` instead of :exc:`Error`.
74
75
76.. exception:: SameFileError
77
78 This exception is raised if source and destination in :func:`copyfile`
79 are the same file.
80
81 .. versionadded:: 3.4
82
83
Larry Hastings7aa2c8b2012-07-15 16:58:29 -070084.. function:: copymode(src, dst, *, follow_symlinks=True)
Georg Brandl116aa622007-08-15 14:28:22 +000085
86 Copy the permission bits from *src* to *dst*. The file contents, owner, and
Larry Hastings60eba572012-09-21 10:12:14 -070087 group are unaffected. *src* and *dst* are path names given as strings.
88 If *follow_symlinks* is false, and both *src* and *dst* are symbolic links,
89 :func:`copymode` will attempt to modify the mode of *dst* itself (rather
90 than the file it points to). This functionality is not available on every
91 platform; please see :func:`copystat` for more information. If
92 :func:`copymode` cannot modify symbolic links on the local platform, and it
93 is asked to do so, it will do nothing and return.
Georg Brandl116aa622007-08-15 14:28:22 +000094
Antoine Pitrou78091e62011-12-29 18:54:15 +010095 .. versionchanged:: 3.3
Larry Hastings7aa2c8b2012-07-15 16:58:29 -070096 Added *follow_symlinks* argument.
Georg Brandl116aa622007-08-15 14:28:22 +000097
Larry Hastings7aa2c8b2012-07-15 16:58:29 -070098.. function:: copystat(src, dst, *, follow_symlinks=True)
Georg Brandl116aa622007-08-15 14:28:22 +000099
Larry Hastings60eba572012-09-21 10:12:14 -0700100 Copy the permission bits, last access time, last modification time, and
101 flags from *src* to *dst*. On Linux, :func:`copystat` also copies the
102 "extended attributes" where possible. The file contents, owner, and
103 group are unaffected. *src* and *dst* are path names given as strings.
104
105 If *follow_symlinks* is false, and *src* and *dst* both
106 refer to symbolic links, :func:`copystat` will operate on
107 the symbolic links themselves rather than the files the
108 symbolic links refer to--reading the information from the
109 *src* symbolic link, and writing the information to the
110 *dst* symbolic link.
111
112 .. note::
113
114 Not all platforms provide the ability to examine and
115 modify symbolic links. Python itself can tell you what
116 functionality is locally available.
117
118 * If ``os.chmod in os.supports_follow_symlinks`` is
119 ``True``, :func:`copystat` can modify the permission
120 bits of a symbolic link.
121
122 * If ``os.utime in os.supports_follow_symlinks`` is
123 ``True``, :func:`copystat` can modify the last access
124 and modification times of a symbolic link.
125
126 * If ``os.chflags in os.supports_follow_symlinks`` is
127 ``True``, :func:`copystat` can modify the flags of
128 a symbolic link. (``os.chflags`` is not available on
129 all platforms.)
130
131 On platforms where some or all of this functionality
132 is unavailable, when asked to modify a symbolic link,
133 :func:`copystat` will copy everything it can.
134 :func:`copystat` never returns failure.
135
136 Please see :data:`os.supports_follow_symlinks`
137 for more information.
Georg Brandl116aa622007-08-15 14:28:22 +0000138
Antoine Pitrou78091e62011-12-29 18:54:15 +0100139 .. versionchanged:: 3.3
Larry Hastings7aa2c8b2012-07-15 16:58:29 -0700140 Added *follow_symlinks* argument and support for Linux extended attributes.
Georg Brandl116aa622007-08-15 14:28:22 +0000141
Larry Hastings7aa2c8b2012-07-15 16:58:29 -0700142.. function:: copy(src, dst, *, follow_symlinks=True)
Georg Brandl116aa622007-08-15 14:28:22 +0000143
Larry Hastings60eba572012-09-21 10:12:14 -0700144 Copies the file *src* to the file or directory *dst*. *src* and *dst*
145 should be strings. If *dst* specifies a directory, the file will be
146 copied into *dst* using the base filename from *src*. Returns the
147 path to the newly created file.
148
149 If *follow_symlinks* is false, and *src* is a symbolic link,
150 *dst* will be created as a symbolic link. If *follow_symlinks*
151 is true and *src* is a symbolic link, *dst* will be a copy of
152 the file *src* refers to.
153
154 :func:`copy` copies the file data and the file's permission
155 mode (see :func:`os.chmod`). Other metadata, like the
156 file's creation and modification times, is not preserved.
157 To preserve all file metadata from the original, use
158 :func:`~shutil.copy2` instead.
Georg Brandl116aa622007-08-15 14:28:22 +0000159
Antoine Pitrou78091e62011-12-29 18:54:15 +0100160 .. versionchanged:: 3.3
Larry Hastings7aa2c8b2012-07-15 16:58:29 -0700161 Added *follow_symlinks* argument.
Larry Hastings60eba572012-09-21 10:12:14 -0700162 Now returns path to the newly created file.
Georg Brandl116aa622007-08-15 14:28:22 +0000163
Larry Hastings7aa2c8b2012-07-15 16:58:29 -0700164.. function:: copy2(src, dst, *, follow_symlinks=True)
Georg Brandl116aa622007-08-15 14:28:22 +0000165
Larry Hastings60eba572012-09-21 10:12:14 -0700166 Identical to :func:`~shutil.copy` except that :func:`copy2`
167 also attempts to preserve all file metadata.
168
169 When *follow_symlinks* is false, and *src* is a symbolic
170 link, :func:`copy2` attempts to copy all metadata from the
171 *src* symbolic link to the newly-created *dst* symbolic link.
172 However, this functionality is not available on all platforms.
173 On platforms where some or all of this functionality is
174 unavailable, :func:`copy2` will preserve all the metadata
175 it can; :func:`copy2` never returns failure.
176
177 :func:`copy2` uses :func:`copystat` to copy the file metadata.
178 Please see :func:`copystat` for more information
179 about platform support for modifying symbolic link metadata.
Georg Brandl116aa622007-08-15 14:28:22 +0000180
Antoine Pitrou78091e62011-12-29 18:54:15 +0100181 .. versionchanged:: 3.3
Larry Hastings7aa2c8b2012-07-15 16:58:29 -0700182 Added *follow_symlinks* argument, try to copy extended
183 file system attributes too (currently Linux only).
Larry Hastings60eba572012-09-21 10:12:14 -0700184 Now returns path to the newly created file.
Brian Curtin066dacf2012-06-19 10:03:05 -0500185
Georg Brandl86b2fb92008-07-16 03:43:04 +0000186.. function:: ignore_patterns(\*patterns)
187
188 This factory function creates a function that can be used as a callable for
189 :func:`copytree`\'s *ignore* argument, ignoring files and directories that
190 match one of the glob-style *patterns* provided. See the example below.
191
192
Ezio Melotticb999a32010-04-20 11:26:51 +0000193.. function:: copytree(src, dst, symlinks=False, ignore=None, copy_function=copy2, ignore_dangling_symlinks=False)
Georg Brandl116aa622007-08-15 14:28:22 +0000194
Brian Curtin0d0a1de2012-06-18 18:41:07 -0500195 Recursively copy an entire directory tree rooted at *src*, returning the
196 destination directory. The destination
Senthil Kumaran7f728c12012-02-13 23:30:47 +0800197 directory, named by *dst*, must not already exist; it will be created as
198 well as missing parent directories. Permissions and times of directories
199 are copied with :func:`copystat`, individual files are copied using
200 :func:`shutil.copy2`.
Georg Brandl116aa622007-08-15 14:28:22 +0000201
Georg Brandl86b2fb92008-07-16 03:43:04 +0000202 If *symlinks* is true, symbolic links in the source tree are represented as
Antoine Pitrou78091e62011-12-29 18:54:15 +0100203 symbolic links in the new tree and the metadata of the original links will
204 be copied as far as the platform allows; if false or omitted, the contents
205 and metadata of the linked files are copied to the new tree.
Georg Brandl86b2fb92008-07-16 03:43:04 +0000206
Tarek Ziadéfb437512010-04-20 08:57:33 +0000207 When *symlinks* is false, if the file pointed by the symlink doesn't
208 exist, a exception will be added in the list of errors raised in
209 a :exc:`Error` exception at the end of the copy process.
210 You can set the optional *ignore_dangling_symlinks* flag to true if you
Tarek Ziadé8c26c7d2010-04-23 13:03:50 +0000211 want to silence this exception. Notice that this option has no effect
212 on platforms that don't support :func:`os.symlink`.
Tarek Ziadéfb437512010-04-20 08:57:33 +0000213
Georg Brandl86b2fb92008-07-16 03:43:04 +0000214 If *ignore* is given, it must be a callable that will receive as its
215 arguments the directory being visited by :func:`copytree`, and a list of its
216 contents, as returned by :func:`os.listdir`. Since :func:`copytree` is
217 called recursively, the *ignore* callable will be called once for each
218 directory that is copied. The callable must return a sequence of directory
219 and file names relative to the current directory (i.e. a subset of the items
220 in its second argument); these names will then be ignored in the copy
221 process. :func:`ignore_patterns` can be used to create such a callable that
222 ignores names based on glob-style patterns.
223
224 If exception(s) occur, an :exc:`Error` is raised with a list of reasons.
225
Senthil Kumaran7f728c12012-02-13 23:30:47 +0800226 If *copy_function* is given, it must be a callable that will be used to copy
227 each file. It will be called with the source path and the destination path
228 as arguments. By default, :func:`shutil.copy2` is used, but any function
Senthil Kumaran1fd64822012-02-13 23:35:44 +0800229 that supports the same signature (like :func:`shutil.copy`) can be used.
Georg Brandl116aa622007-08-15 14:28:22 +0000230
Larry Hastings7aa2c8b2012-07-15 16:58:29 -0700231 .. versionchanged:: 3.3
232 Copy metadata when *symlinks* is false.
233 Now returns *dst*.
234
Tarek Ziadé5340db32010-04-19 22:30:51 +0000235 .. versionchanged:: 3.2
236 Added the *copy_function* argument to be able to provide a custom copy
237 function.
Tarek Ziadéfb437512010-04-20 08:57:33 +0000238 Added the *ignore_dangling_symlinks* argument to silent dangling symlinks
239 errors when *symlinks* is false.
240
Georg Brandl96acb732012-06-24 17:39:05 +0200241
Georg Brandl18244152009-09-02 20:34:52 +0000242.. function:: rmtree(path, ignore_errors=False, onerror=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000243
244 .. index:: single: directory; deleting
245
Christian Heimes9bd667a2008-01-20 15:14:11 +0000246 Delete an entire directory tree; *path* must point to a directory (but not a
247 symbolic link to a directory). If *ignore_errors* is true, errors resulting
248 from failed removals will be ignored; if false or omitted, such errors are
249 handled by calling a handler specified by *onerror* or, if that is omitted,
250 they raise an exception.
Georg Brandl116aa622007-08-15 14:28:22 +0000251
Nick Coghlan5b0eca12012-06-24 16:43:06 +1000252 .. note::
Hynek Schlawack67be92b2012-06-23 17:58:42 +0200253
Nick Coghlan5b0eca12012-06-24 16:43:06 +1000254 On platforms that support the necessary fd-based functions a symlink
Georg Brandl96acb732012-06-24 17:39:05 +0200255 attack resistant version of :func:`rmtree` is used by default. On other
256 platforms, the :func:`rmtree` implementation is susceptible to a symlink
257 attack: given proper timing and circumstances, attackers can manipulate
258 symlinks on the filesystem to delete files they wouldn't be able to access
259 otherwise. Applications can use the :data:`rmtree.avoids_symlink_attacks`
260 function attribute to determine which case applies.
Hynek Schlawack67be92b2012-06-23 17:58:42 +0200261
Christian Heimes9bd667a2008-01-20 15:14:11 +0000262 If *onerror* is provided, it must be a callable that accepts three
Hynek Schlawack67be92b2012-06-23 17:58:42 +0200263 parameters: *function*, *path*, and *excinfo*.
264
265 The first parameter, *function*, is the function which raised the exception;
266 it depends on the platform and implementation. The second parameter,
267 *path*, will be the path name passed to *function*. The third parameter,
268 *excinfo*, will be the exception information returned by
269 :func:`sys.exc_info`. Exceptions raised by *onerror* will not be caught.
270
271 .. versionchanged:: 3.3
Nick Coghlan5b0eca12012-06-24 16:43:06 +1000272 Added a symlink attack resistant version that is used automatically
273 if platform supports fd-based functions.
Christian Heimes9bd667a2008-01-20 15:14:11 +0000274
Éric Araujo544e13d2012-06-24 13:53:48 -0400275 .. attribute:: rmtree.avoids_symlink_attacks
Hynek Schlawack2100b422012-06-23 20:28:32 +0200276
Nick Coghlan5b0eca12012-06-24 16:43:06 +1000277 Indicates whether the current platform and implementation provides a
Georg Brandl96acb732012-06-24 17:39:05 +0200278 symlink attack resistant version of :func:`rmtree`. Currently this is
Nick Coghlan5b0eca12012-06-24 16:43:06 +1000279 only true for platforms supporting fd-based directory access functions.
Hynek Schlawack2100b422012-06-23 20:28:32 +0200280
Nick Coghlan5b0eca12012-06-24 16:43:06 +1000281 .. versionadded:: 3.3
Georg Brandl116aa622007-08-15 14:28:22 +0000282
Georg Brandl96acb732012-06-24 17:39:05 +0200283
Georg Brandl116aa622007-08-15 14:28:22 +0000284.. function:: move(src, dst)
285
Brian Curtin0d0a1de2012-06-18 18:41:07 -0500286 Recursively move a file or directory (*src*) to another location (*dst*)
287 and return the destination.
Georg Brandl116aa622007-08-15 14:28:22 +0000288
Éric Araujo14382dc2011-07-28 22:49:11 +0200289 If the destination is a directory or a symlink to a directory, then *src* is
290 moved inside that directory.
291
292 The destination directory must not already exist. If the destination already
293 exists but is not a directory, it may be overwritten depending on
294 :func:`os.rename` semantics.
295
296 If the destination is on the current filesystem, then :func:`os.rename` is
Senthil Kumaran7f728c12012-02-13 23:30:47 +0800297 used. Otherwise, *src* is copied (using :func:`shutil.copy2`) to *dst* and
Senthil Kumaran1fd64822012-02-13 23:35:44 +0800298 then removed. In case of symlinks, a new symlink pointing to the target of
299 *src* will be created in or as *dst* and *src* will be removed.
Antoine Pitrou0a08d7a2012-01-06 20:16:19 +0100300
301 .. versionchanged:: 3.3
302 Added explicit symlink handling for foreign filesystems, thus adapting
303 it to the behavior of GNU's :program:`mv`.
Larry Hastings7aa2c8b2012-07-15 16:58:29 -0700304 Now returns *dst*.
Brian Curtin066dacf2012-06-19 10:03:05 -0500305
Giampaolo Rodola'210e7ca2011-07-01 13:55:36 +0200306.. function:: disk_usage(path)
307
Éric Araujoe4d5b8e2011-08-08 16:51:11 +0200308 Return disk usage statistics about the given path as a :term:`named tuple`
309 with the attributes *total*, *used* and *free*, which are the amount of
310 total, used and free space, in bytes.
Giampaolo Rodola'210e7ca2011-07-01 13:55:36 +0200311
312 .. versionadded:: 3.3
313
314 Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000315
Sandro Tosid902a142011-08-22 23:28:27 +0200316.. function:: chown(path, user=None, group=None)
317
318 Change owner *user* and/or *group* of the given *path*.
319
320 *user* can be a system user name or a uid; the same applies to *group*. At
321 least one argument is required.
322
323 See also :func:`os.chown`, the underlying function.
324
325 Availability: Unix.
326
327 .. versionadded:: 3.3
328
Georg Brandl4a7e25f2012-06-24 17:37:07 +0200329
Brian Curtinc57a3452012-06-22 16:00:30 -0500330.. function:: which(cmd, mode=os.F_OK | os.X_OK, path=None)
331
Georg Brandl4a7e25f2012-06-24 17:37:07 +0200332 Return the path to an executable which would be run if the given *cmd* was
333 called. If no *cmd* would be called, return ``None``.
Brian Curtinc57a3452012-06-22 16:00:30 -0500334
335 *mode* is a permission mask passed a to :func:`os.access`, by default
336 determining if the file exists and executable.
337
Georg Brandl4a7e25f2012-06-24 17:37:07 +0200338 When no *path* is specified, the results of :func:`os.environ` are used,
339 returning either the "PATH" value or a fallback of :attr:`os.defpath`.
Brian Curtinc57a3452012-06-22 16:00:30 -0500340
Georg Brandl4a7e25f2012-06-24 17:37:07 +0200341 On Windows, the current directory is always prepended to the *path* whether
342 or not you use the default or provide your own, which is the behavior the
343 command shell uses when finding executables. Additionaly, when finding the
344 *cmd* in the *path*, the ``PATHEXT`` environment variable is checked. For
345 example, if you call ``shutil.which("python")``, :func:`which` will search
346 ``PATHEXT`` to know that it should look for ``python.exe`` within the *path*
347 directories. For example, on Windows::
Brian Curtinc57a3452012-06-22 16:00:30 -0500348
Georg Brandl4a7e25f2012-06-24 17:37:07 +0200349 >>> shutil.which("python")
Brian Curtinc57a3452012-06-22 16:00:30 -0500350 'c:\\python33\\python.exe'
351
352 .. versionadded:: 3.3
Sandro Tosid902a142011-08-22 23:28:27 +0200353
Georg Brandl4a7e25f2012-06-24 17:37:07 +0200354
Georg Brandl116aa622007-08-15 14:28:22 +0000355.. exception:: Error
356
Éric Araujo14382dc2011-07-28 22:49:11 +0200357 This exception collects exceptions that are raised during a multi-file
358 operation. For :func:`copytree`, the exception argument is a list of 3-tuples
359 (*srcname*, *dstname*, *exception*).
Georg Brandl116aa622007-08-15 14:28:22 +0000360
Georg Brandl116aa622007-08-15 14:28:22 +0000361
Éric Araujof2fbb9c2012-01-16 16:55:55 +0100362.. _shutil-copytree-example:
Georg Brandl116aa622007-08-15 14:28:22 +0000363
Tarek Ziadé396fad72010-02-23 05:30:31 +0000364copytree example
Georg Brandl03b9ad02012-06-24 18:09:40 +0200365~~~~~~~~~~~~~~~~
Georg Brandl116aa622007-08-15 14:28:22 +0000366
367This example is the implementation of the :func:`copytree` function, described
368above, with the docstring omitted. It demonstrates many of the other functions
369provided by this module. ::
370
371 def copytree(src, dst, symlinks=False):
372 names = os.listdir(src)
373 os.makedirs(dst)
374 errors = []
375 for name in names:
376 srcname = os.path.join(src, name)
377 dstname = os.path.join(dst, name)
378 try:
379 if symlinks and os.path.islink(srcname):
380 linkto = os.readlink(srcname)
381 os.symlink(linkto, dstname)
382 elif os.path.isdir(srcname):
383 copytree(srcname, dstname, symlinks)
384 else:
385 copy2(srcname, dstname)
386 # XXX What about devices, sockets etc.?
387 except (IOError, os.error) as why:
388 errors.append((srcname, dstname, str(why)))
389 # catch the Error from the recursive copytree so that we can
390 # continue with other files
391 except Error as err:
392 errors.extend(err.args[0])
393 try:
394 copystat(src, dst)
395 except WindowsError:
396 # can't copy file access times on Windows
397 pass
398 except OSError as why:
399 errors.extend((src, dst, str(why)))
400 if errors:
Collin Winterc79461b2007-09-01 23:34:30 +0000401 raise Error(errors)
Georg Brandl116aa622007-08-15 14:28:22 +0000402
Tarek Ziadé396fad72010-02-23 05:30:31 +0000403Another example that uses the :func:`ignore_patterns` helper::
404
405 from shutil import copytree, ignore_patterns
406
407 copytree(source, destination, ignore=ignore_patterns('*.pyc', 'tmp*'))
408
409This will copy everything except ``.pyc`` files and files or directories whose
410name starts with ``tmp``.
411
412Another example that uses the *ignore* argument to add a logging call::
413
414 from shutil import copytree
415 import logging
416
417 def _logpath(path, names):
418 logging.info('Working in %s' % path)
419 return [] # nothing will be ignored
420
421 copytree(source, destination, ignore=_logpath)
422
423
Raymond Hettinger0929b1f2011-01-23 11:29:08 +0000424.. _archiving-operations:
425
426Archiving operations
427--------------------
Tarek Ziadé396fad72010-02-23 05:30:31 +0000428
Georg Brandl03b9ad02012-06-24 18:09:40 +0200429.. versionadded:: 3.2
430
Éric Araujof2fbb9c2012-01-16 16:55:55 +0100431High-level utilities to create and read compressed and archived files are also
432provided. They rely on the :mod:`zipfile` and :mod:`tarfile` modules.
433
Tarek Ziadé396fad72010-02-23 05:30:31 +0000434.. function:: make_archive(base_name, format, [root_dir, [base_dir, [verbose, [dry_run, [owner, [group, [logger]]]]]]])
435
Raymond Hettinger0929b1f2011-01-23 11:29:08 +0000436 Create an archive file (such as zip or tar) and return its name.
Tarek Ziadé396fad72010-02-23 05:30:31 +0000437
438 *base_name* is the name of the file to create, including the path, minus
439 any format-specific extension. *format* is the archive format: one of
Tarek Ziadéffa155a2010-04-29 13:34:35 +0000440 "zip", "tar", "bztar" (if the :mod:`bz2` module is available) or "gztar".
Tarek Ziadé396fad72010-02-23 05:30:31 +0000441
442 *root_dir* is a directory that will be the root directory of the
Raymond Hettinger0929b1f2011-01-23 11:29:08 +0000443 archive; for example, we typically chdir into *root_dir* before creating the
Tarek Ziadé396fad72010-02-23 05:30:31 +0000444 archive.
445
446 *base_dir* is the directory where we start archiving from;
Ezio Melotticb999a32010-04-20 11:26:51 +0000447 i.e. *base_dir* will be the common prefix of all files and
Tarek Ziadé396fad72010-02-23 05:30:31 +0000448 directories in the archive.
449
450 *root_dir* and *base_dir* both default to the current directory.
451
452 *owner* and *group* are used when creating a tar archive. By default,
453 uses the current owner and group.
454
Éric Araujo06c42a32011-11-07 17:31:07 +0100455 *logger* must be an object compatible with :pep:`282`, usually an instance of
456 :class:`logging.Logger`.
Raymond Hettinger0929b1f2011-01-23 11:29:08 +0000457
Tarek Ziadé396fad72010-02-23 05:30:31 +0000458
459.. function:: get_archive_formats()
460
Éric Araujo14382dc2011-07-28 22:49:11 +0200461 Return a list of supported formats for archiving.
Tarek Ziadé396fad72010-02-23 05:30:31 +0000462 Each element of the returned sequence is a tuple ``(name, description)``
463
464 By default :mod:`shutil` provides these formats:
465
466 - *gztar*: gzip'ed tar-file
Tarek Ziadéffa155a2010-04-29 13:34:35 +0000467 - *bztar*: bzip2'ed tar-file (if the :mod:`bz2` module is available.)
Tarek Ziadé396fad72010-02-23 05:30:31 +0000468 - *tar*: uncompressed tar file
469 - *zip*: ZIP file
470
471 You can register new formats or provide your own archiver for any existing
472 formats, by using :func:`register_archive_format`.
473
Tarek Ziadé396fad72010-02-23 05:30:31 +0000474
475.. function:: register_archive_format(name, function, [extra_args, [description]])
476
Éric Araujo14382dc2011-07-28 22:49:11 +0200477 Register an archiver for the format *name*. *function* is a callable that
Tarek Ziadé396fad72010-02-23 05:30:31 +0000478 will be used to invoke the archiver.
479
Raymond Hettinger0929b1f2011-01-23 11:29:08 +0000480 If given, *extra_args* is a sequence of ``(name, value)`` pairs that will be
Tarek Ziadé396fad72010-02-23 05:30:31 +0000481 used as extra keywords arguments when the archiver callable is used.
482
483 *description* is used by :func:`get_archive_formats` which returns the
484 list of archivers. Defaults to an empty list.
485
Tarek Ziadé396fad72010-02-23 05:30:31 +0000486
Tarek Ziadé6ac91722010-04-28 17:51:36 +0000487.. function:: unregister_archive_format(name)
Tarek Ziadé396fad72010-02-23 05:30:31 +0000488
489 Remove the archive format *name* from the list of supported formats.
490
Tarek Ziadé396fad72010-02-23 05:30:31 +0000491
Tarek Ziadé6ac91722010-04-28 17:51:36 +0000492.. function:: unpack_archive(filename[, extract_dir[, format]])
493
494 Unpack an archive. *filename* is the full path of the archive.
495
496 *extract_dir* is the name of the target directory where the archive is
497 unpacked. If not provided, the current working directory is used.
498
499 *format* is the archive format: one of "zip", "tar", or "gztar". Or any
500 other format registered with :func:`register_unpack_format`. If not
501 provided, :func:`unpack_archive` will use the archive file name extension
502 and see if an unpacker was registered for that extension. In case none is
503 found, a :exc:`ValueError` is raised.
504
Tarek Ziadé6ac91722010-04-28 17:51:36 +0000505
Raymond Hettinger0929b1f2011-01-23 11:29:08 +0000506.. function:: register_unpack_format(name, extensions, function[, extra_args[, description]])
Tarek Ziadé6ac91722010-04-28 17:51:36 +0000507
508 Registers an unpack format. *name* is the name of the format and
509 *extensions* is a list of extensions corresponding to the format, like
510 ``.zip`` for Zip files.
511
512 *function* is the callable that will be used to unpack archives. The
513 callable will receive the path of the archive, followed by the directory
514 the archive must be extracted to.
515
516 When provided, *extra_args* is a sequence of ``(name, value)`` tuples that
517 will be passed as keywords arguments to the callable.
518
519 *description* can be provided to describe the format, and will be returned
520 by the :func:`get_unpack_formats` function.
521
Tarek Ziadé6ac91722010-04-28 17:51:36 +0000522
523.. function:: unregister_unpack_format(name)
524
525 Unregister an unpack format. *name* is the name of the format.
526
Tarek Ziadé6ac91722010-04-28 17:51:36 +0000527
528.. function:: get_unpack_formats()
529
530 Return a list of all registered formats for unpacking.
531 Each element of the returned sequence is a tuple
532 ``(name, extensions, description)``.
533
534 By default :mod:`shutil` provides these formats:
535
536 - *gztar*: gzip'ed tar-file
Tarek Ziadéffa155a2010-04-29 13:34:35 +0000537 - *bztar*: bzip2'ed tar-file (if the :mod:`bz2` module is available.)
Tarek Ziadé6ac91722010-04-28 17:51:36 +0000538 - *tar*: uncompressed tar file
539 - *zip*: ZIP file
540
541 You can register new formats or provide your own unpacker for any existing
542 formats, by using :func:`register_unpack_format`.
543
Tarek Ziadé6ac91722010-04-28 17:51:36 +0000544
Éric Araujof2fbb9c2012-01-16 16:55:55 +0100545.. _shutil-archiving-example:
Tarek Ziadé6ac91722010-04-28 17:51:36 +0000546
Tarek Ziadé396fad72010-02-23 05:30:31 +0000547Archiving example
Georg Brandl03b9ad02012-06-24 18:09:40 +0200548~~~~~~~~~~~~~~~~~
Tarek Ziadé396fad72010-02-23 05:30:31 +0000549
550In this example, we create a gzip'ed tar-file archive containing all files
551found in the :file:`.ssh` directory of the user::
552
553 >>> from shutil import make_archive
554 >>> import os
555 >>> archive_name = os.path.expanduser(os.path.join('~', 'myarchive'))
556 >>> root_dir = os.path.expanduser(os.path.join('~', '.ssh'))
557 >>> make_archive(archive_name, 'gztar', root_dir)
558 '/Users/tarek/myarchive.tar.gz'
559
560The resulting archive contains::
561
562 $ tar -tzvf /Users/tarek/myarchive.tar.gz
563 drwx------ tarek/staff 0 2010-02-01 16:23:40 ./
564 -rw-r--r-- tarek/staff 609 2008-06-09 13:26:54 ./authorized_keys
565 -rwxr-xr-x tarek/staff 65 2008-06-09 13:26:54 ./config
566 -rwx------ tarek/staff 668 2008-06-09 13:26:54 ./id_dsa
567 -rwxr-xr-x tarek/staff 609 2008-06-09 13:26:54 ./id_dsa.pub
568 -rw------- tarek/staff 1675 2008-06-09 13:26:54 ./id_rsa
569 -rw-r--r-- tarek/staff 397 2008-06-09 13:26:54 ./id_rsa.pub
570 -rw-r--r-- tarek/staff 37192 2010-02-06 18:23:10 ./known_hosts
Antoine Pitroubcf2b592012-02-08 23:28:36 +0100571
572
573Querying the size of the output terminal
574----------------------------------------
575
576.. versionadded:: 3.3
577
578.. function:: get_terminal_size(fallback=(columns, lines))
579
580 Get the size of the terminal window.
581
582 For each of the two dimensions, the environment variable, ``COLUMNS``
583 and ``LINES`` respectively, is checked. If the variable is defined and
584 the value is a positive integer, it is used.
585
586 When ``COLUMNS`` or ``LINES`` is not defined, which is the common case,
587 the terminal connected to :data:`sys.__stdout__` is queried
588 by invoking :func:`os.get_terminal_size`.
589
590 If the terminal size cannot be successfully queried, either because
591 the system doesn't support querying, or because we are not
592 connected to a terminal, the value given in ``fallback`` parameter
593 is used. ``fallback`` defaults to ``(80, 24)`` which is the default
594 size used by many terminal emulators.
595
596 The value returned is a named tuple of type :class:`os.terminal_size`.
597
598 See also: The Single UNIX Specification, Version 2,
599 `Other Environment Variables`_.
600
601.. _`Other Environment Variables`:
602 http://pubs.opengroup.org/onlinepubs/7908799/xbd/envvar.html#tag_002_003
603