blob: d0191371971ddb7feb6488aad610926b55ef221e [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
Brian Curtin0d0a1de2012-06-18 18:41:07 -050053 *dst* and return *dst*. *dst* must be the complete target file name; look at
Senthil Kumaran7f728c12012-02-13 23:30:47 +080054 :func:`shutil.copy` for a copy that accepts a target directory path. If
Hynek Schlawack77d32832012-07-19 20:23:49 +020055 *src* and *dst* are the same files, :exc:`SameFileError` is raised.
Senthil Kumaran1fd64822012-02-13 23:35:44 +080056
Antoine Pitrou62ab10a2011-10-12 20:10:51 +020057 The destination location must be writable; otherwise, an :exc:`OSError` exception
Christian Heimesa342c012008-04-20 21:01:16 +000058 will be raised. If *dst* already exists, it will be replaced. Special files
59 such as character or block devices and pipes cannot be copied with this
60 function. *src* and *dst* are path names given as strings.
61
Larry Hastings7aa2c8b2012-07-15 16:58:29 -070062 If *follow_symlinks* is false and *src* is a symbolic link,
63 a new symbolic link will be created instead of copying the
64 file *src* points to.
Antoine Pitrou78091e62011-12-29 18:54:15 +010065
Antoine Pitrou62ab10a2011-10-12 20:10:51 +020066 .. versionchanged:: 3.3
67 :exc:`IOError` used to be raised instead of :exc:`OSError`.
Larry Hastings7aa2c8b2012-07-15 16:58:29 -070068 Added *follow_symlinks* argument.
69 Now returns *dst*.
Hynek Schlawack77d32832012-07-19 20:23:49 +020070 Raise :exc:`SameFileError` instead of :exc:`Error`.
71
72
73.. exception:: SameFileError
74
75 This exception is raised if source and destination in :func:`copyfile`
76 are the same file.
77
78 .. versionadded:: 3.3
79
Antoine Pitrou62ab10a2011-10-12 20:10:51 +020080
Larry Hastings7aa2c8b2012-07-15 16:58:29 -070081.. function:: copymode(src, dst, *, follow_symlinks=True)
Georg Brandl116aa622007-08-15 14:28:22 +000082
83 Copy the permission bits from *src* to *dst*. The file contents, owner, and
Antoine Pitrou78091e62011-12-29 18:54:15 +010084 group are unaffected. *src* and *dst* are path names given as strings. If
Larry Hastings7aa2c8b2012-07-15 16:58:29 -070085 *follow_symlinks* is false, *src* is a symbolic link, and the operating
86 system supports modes for symbolic links (for example BSD-based ones),
87 the mode of the link will be copied.
Georg Brandl116aa622007-08-15 14:28:22 +000088
Antoine Pitrou78091e62011-12-29 18:54:15 +010089 .. versionchanged:: 3.3
Larry Hastings7aa2c8b2012-07-15 16:58:29 -070090 Added *follow_symlinks* argument.
Georg Brandl116aa622007-08-15 14:28:22 +000091
Larry Hastings7aa2c8b2012-07-15 16:58:29 -070092.. function:: copystat(src, dst, *, follow_symlinks=True)
Georg Brandl116aa622007-08-15 14:28:22 +000093
94 Copy the permission bits, last access time, last modification time, and flags
95 from *src* to *dst*. The file contents, owner, and group are unaffected. *src*
Larry Hastings7aa2c8b2012-07-15 16:58:29 -070096 and *dst* are path names given as strings. If *follow_symlinks* is false, and
97 *src* and *dst* are both symbolic links, the stats of the link will be copied as
Larry Hastingsad5ae042012-07-14 17:55:11 -070098 far as the platform allows. On Linux, :func:`copystat` also copies the
99 "extended attributes" where possible.
Georg Brandl116aa622007-08-15 14:28:22 +0000100
Antoine Pitrou78091e62011-12-29 18:54:15 +0100101 .. versionchanged:: 3.3
Larry Hastings7aa2c8b2012-07-15 16:58:29 -0700102 Added *follow_symlinks* argument and support for Linux extended attributes.
Georg Brandl116aa622007-08-15 14:28:22 +0000103
Larry Hastings7aa2c8b2012-07-15 16:58:29 -0700104.. function:: copy(src, dst, *, follow_symlinks=True)
Georg Brandl116aa622007-08-15 14:28:22 +0000105
Brian Curtin0d0a1de2012-06-18 18:41:07 -0500106 Copy the file *src* to the file or directory *dst* and return the file's
107 destination. If *dst* is a directory, a
Georg Brandl116aa622007-08-15 14:28:22 +0000108 file with the same basename as *src* is created (or overwritten) in the
109 directory specified. Permission bits are copied. *src* and *dst* are path
Larry Hastings7aa2c8b2012-07-15 16:58:29 -0700110 names given as strings. If *follow_symlinks* is false, symbolic
111 links won't be followed but recreated instead -- this resembles GNU's
112 :program:`cp -P`.
Georg Brandl116aa622007-08-15 14:28:22 +0000113
Antoine Pitrou78091e62011-12-29 18:54:15 +0100114 .. versionchanged:: 3.3
Larry Hastings7aa2c8b2012-07-15 16:58:29 -0700115 Added *follow_symlinks* argument.
116 Now returns *dst*.
Georg Brandl116aa622007-08-15 14:28:22 +0000117
Larry Hastings7aa2c8b2012-07-15 16:58:29 -0700118.. function:: copy2(src, dst, *, follow_symlinks=True)
Georg Brandl116aa622007-08-15 14:28:22 +0000119
Brian Curtin0d0a1de2012-06-18 18:41:07 -0500120 Similar to :func:`shutil.copy`, including that the destination is
Larry Hastings7aa2c8b2012-07-15 16:58:29 -0700121 returned, but metadata is copied as well. This is similar to the Unix
122 command :program:`cp -p`. If *follow_symlinks* is false,
Senthil Kumaran1fd64822012-02-13 23:35:44 +0800123 symbolic links won't be followed but recreated instead -- this resembles
124 GNU's :program:`cp -P`.
Georg Brandl116aa622007-08-15 14:28:22 +0000125
Antoine Pitrou78091e62011-12-29 18:54:15 +0100126 .. versionchanged:: 3.3
Larry Hastings7aa2c8b2012-07-15 16:58:29 -0700127 Added *follow_symlinks* argument, try to copy extended
128 file system attributes too (currently Linux only).
129 Now returns *dst*.
Brian Curtin066dacf2012-06-19 10:03:05 -0500130
Georg Brandl86b2fb92008-07-16 03:43:04 +0000131.. function:: ignore_patterns(\*patterns)
132
133 This factory function creates a function that can be used as a callable for
134 :func:`copytree`\'s *ignore* argument, ignoring files and directories that
135 match one of the glob-style *patterns* provided. See the example below.
136
137
Ezio Melotticb999a32010-04-20 11:26:51 +0000138.. function:: copytree(src, dst, symlinks=False, ignore=None, copy_function=copy2, ignore_dangling_symlinks=False)
Georg Brandl116aa622007-08-15 14:28:22 +0000139
Brian Curtin0d0a1de2012-06-18 18:41:07 -0500140 Recursively copy an entire directory tree rooted at *src*, returning the
141 destination directory. The destination
Senthil Kumaran7f728c12012-02-13 23:30:47 +0800142 directory, named by *dst*, must not already exist; it will be created as
143 well as missing parent directories. Permissions and times of directories
144 are copied with :func:`copystat`, individual files are copied using
145 :func:`shutil.copy2`.
Georg Brandl116aa622007-08-15 14:28:22 +0000146
Georg Brandl86b2fb92008-07-16 03:43:04 +0000147 If *symlinks* is true, symbolic links in the source tree are represented as
Antoine Pitrou78091e62011-12-29 18:54:15 +0100148 symbolic links in the new tree and the metadata of the original links will
149 be copied as far as the platform allows; if false or omitted, the contents
150 and metadata of the linked files are copied to the new tree.
Georg Brandl86b2fb92008-07-16 03:43:04 +0000151
Tarek Ziadéfb437512010-04-20 08:57:33 +0000152 When *symlinks* is false, if the file pointed by the symlink doesn't
153 exist, a exception will be added in the list of errors raised in
154 a :exc:`Error` exception at the end of the copy process.
155 You can set the optional *ignore_dangling_symlinks* flag to true if you
Tarek Ziadé8c26c7d2010-04-23 13:03:50 +0000156 want to silence this exception. Notice that this option has no effect
157 on platforms that don't support :func:`os.symlink`.
Tarek Ziadéfb437512010-04-20 08:57:33 +0000158
Georg Brandl86b2fb92008-07-16 03:43:04 +0000159 If *ignore* is given, it must be a callable that will receive as its
160 arguments the directory being visited by :func:`copytree`, and a list of its
161 contents, as returned by :func:`os.listdir`. Since :func:`copytree` is
162 called recursively, the *ignore* callable will be called once for each
163 directory that is copied. The callable must return a sequence of directory
164 and file names relative to the current directory (i.e. a subset of the items
165 in its second argument); these names will then be ignored in the copy
166 process. :func:`ignore_patterns` can be used to create such a callable that
167 ignores names based on glob-style patterns.
168
169 If exception(s) occur, an :exc:`Error` is raised with a list of reasons.
170
Senthil Kumaran7f728c12012-02-13 23:30:47 +0800171 If *copy_function* is given, it must be a callable that will be used to copy
172 each file. It will be called with the source path and the destination path
173 as arguments. By default, :func:`shutil.copy2` is used, but any function
Senthil Kumaran1fd64822012-02-13 23:35:44 +0800174 that supports the same signature (like :func:`shutil.copy`) can be used.
Georg Brandl116aa622007-08-15 14:28:22 +0000175
Larry Hastings7aa2c8b2012-07-15 16:58:29 -0700176 .. versionchanged:: 3.3
177 Copy metadata when *symlinks* is false.
178 Now returns *dst*.
179
Tarek Ziadé5340db32010-04-19 22:30:51 +0000180 .. versionchanged:: 3.2
181 Added the *copy_function* argument to be able to provide a custom copy
182 function.
Tarek Ziadéfb437512010-04-20 08:57:33 +0000183 Added the *ignore_dangling_symlinks* argument to silent dangling symlinks
184 errors when *symlinks* is false.
185
Georg Brandl96acb732012-06-24 17:39:05 +0200186
Georg Brandl18244152009-09-02 20:34:52 +0000187.. function:: rmtree(path, ignore_errors=False, onerror=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000188
189 .. index:: single: directory; deleting
190
Christian Heimes9bd667a2008-01-20 15:14:11 +0000191 Delete an entire directory tree; *path* must point to a directory (but not a
192 symbolic link to a directory). If *ignore_errors* is true, errors resulting
193 from failed removals will be ignored; if false or omitted, such errors are
194 handled by calling a handler specified by *onerror* or, if that is omitted,
195 they raise an exception.
Georg Brandl116aa622007-08-15 14:28:22 +0000196
Nick Coghlan5b0eca12012-06-24 16:43:06 +1000197 .. note::
Hynek Schlawack67be92b2012-06-23 17:58:42 +0200198
Nick Coghlan5b0eca12012-06-24 16:43:06 +1000199 On platforms that support the necessary fd-based functions a symlink
Georg Brandl96acb732012-06-24 17:39:05 +0200200 attack resistant version of :func:`rmtree` is used by default. On other
201 platforms, the :func:`rmtree` implementation is susceptible to a symlink
202 attack: given proper timing and circumstances, attackers can manipulate
203 symlinks on the filesystem to delete files they wouldn't be able to access
204 otherwise. Applications can use the :data:`rmtree.avoids_symlink_attacks`
205 function attribute to determine which case applies.
Hynek Schlawack67be92b2012-06-23 17:58:42 +0200206
Christian Heimes9bd667a2008-01-20 15:14:11 +0000207 If *onerror* is provided, it must be a callable that accepts three
Hynek Schlawack67be92b2012-06-23 17:58:42 +0200208 parameters: *function*, *path*, and *excinfo*.
209
210 The first parameter, *function*, is the function which raised the exception;
211 it depends on the platform and implementation. The second parameter,
212 *path*, will be the path name passed to *function*. The third parameter,
213 *excinfo*, will be the exception information returned by
214 :func:`sys.exc_info`. Exceptions raised by *onerror* will not be caught.
215
216 .. versionchanged:: 3.3
Nick Coghlan5b0eca12012-06-24 16:43:06 +1000217 Added a symlink attack resistant version that is used automatically
218 if platform supports fd-based functions.
Christian Heimes9bd667a2008-01-20 15:14:11 +0000219
Éric Araujo544e13d2012-06-24 13:53:48 -0400220 .. attribute:: rmtree.avoids_symlink_attacks
Hynek Schlawack2100b422012-06-23 20:28:32 +0200221
Nick Coghlan5b0eca12012-06-24 16:43:06 +1000222 Indicates whether the current platform and implementation provides a
Georg Brandl96acb732012-06-24 17:39:05 +0200223 symlink attack resistant version of :func:`rmtree`. Currently this is
Nick Coghlan5b0eca12012-06-24 16:43:06 +1000224 only true for platforms supporting fd-based directory access functions.
Hynek Schlawack2100b422012-06-23 20:28:32 +0200225
Nick Coghlan5b0eca12012-06-24 16:43:06 +1000226 .. versionadded:: 3.3
Georg Brandl116aa622007-08-15 14:28:22 +0000227
Georg Brandl96acb732012-06-24 17:39:05 +0200228
Georg Brandl116aa622007-08-15 14:28:22 +0000229.. function:: move(src, dst)
230
Brian Curtin0d0a1de2012-06-18 18:41:07 -0500231 Recursively move a file or directory (*src*) to another location (*dst*)
232 and return the destination.
Georg Brandl116aa622007-08-15 14:28:22 +0000233
Éric Araujo14382dc2011-07-28 22:49:11 +0200234 If the destination is a directory or a symlink to a directory, then *src* is
235 moved inside that directory.
236
237 The destination directory must not already exist. If the destination already
238 exists but is not a directory, it may be overwritten depending on
239 :func:`os.rename` semantics.
240
241 If the destination is on the current filesystem, then :func:`os.rename` is
Senthil Kumaran7f728c12012-02-13 23:30:47 +0800242 used. Otherwise, *src* is copied (using :func:`shutil.copy2`) to *dst* and
Senthil Kumaran1fd64822012-02-13 23:35:44 +0800243 then removed. In case of symlinks, a new symlink pointing to the target of
244 *src* will be created in or as *dst* and *src* will be removed.
Antoine Pitrou0a08d7a2012-01-06 20:16:19 +0100245
246 .. versionchanged:: 3.3
247 Added explicit symlink handling for foreign filesystems, thus adapting
248 it to the behavior of GNU's :program:`mv`.
Larry Hastings7aa2c8b2012-07-15 16:58:29 -0700249 Now returns *dst*.
Brian Curtin066dacf2012-06-19 10:03:05 -0500250
Giampaolo Rodola'210e7ca2011-07-01 13:55:36 +0200251.. function:: disk_usage(path)
252
Éric Araujoe4d5b8e2011-08-08 16:51:11 +0200253 Return disk usage statistics about the given path as a :term:`named tuple`
254 with the attributes *total*, *used* and *free*, which are the amount of
255 total, used and free space, in bytes.
Giampaolo Rodola'210e7ca2011-07-01 13:55:36 +0200256
257 .. versionadded:: 3.3
258
259 Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000260
Sandro Tosid902a142011-08-22 23:28:27 +0200261.. function:: chown(path, user=None, group=None)
262
263 Change owner *user* and/or *group* of the given *path*.
264
265 *user* can be a system user name or a uid; the same applies to *group*. At
266 least one argument is required.
267
268 See also :func:`os.chown`, the underlying function.
269
270 Availability: Unix.
271
272 .. versionadded:: 3.3
273
Georg Brandl4a7e25f2012-06-24 17:37:07 +0200274
Brian Curtinc57a3452012-06-22 16:00:30 -0500275.. function:: which(cmd, mode=os.F_OK | os.X_OK, path=None)
276
Georg Brandl4a7e25f2012-06-24 17:37:07 +0200277 Return the path to an executable which would be run if the given *cmd* was
278 called. If no *cmd* would be called, return ``None``.
Brian Curtinc57a3452012-06-22 16:00:30 -0500279
280 *mode* is a permission mask passed a to :func:`os.access`, by default
281 determining if the file exists and executable.
282
Georg Brandl4a7e25f2012-06-24 17:37:07 +0200283 When no *path* is specified, the results of :func:`os.environ` are used,
284 returning either the "PATH" value or a fallback of :attr:`os.defpath`.
Brian Curtinc57a3452012-06-22 16:00:30 -0500285
Georg Brandl4a7e25f2012-06-24 17:37:07 +0200286 On Windows, the current directory is always prepended to the *path* whether
287 or not you use the default or provide your own, which is the behavior the
288 command shell uses when finding executables. Additionaly, when finding the
289 *cmd* in the *path*, the ``PATHEXT`` environment variable is checked. For
290 example, if you call ``shutil.which("python")``, :func:`which` will search
291 ``PATHEXT`` to know that it should look for ``python.exe`` within the *path*
292 directories. For example, on Windows::
Brian Curtinc57a3452012-06-22 16:00:30 -0500293
Georg Brandl4a7e25f2012-06-24 17:37:07 +0200294 >>> shutil.which("python")
Brian Curtinc57a3452012-06-22 16:00:30 -0500295 'c:\\python33\\python.exe'
296
297 .. versionadded:: 3.3
Sandro Tosid902a142011-08-22 23:28:27 +0200298
Georg Brandl4a7e25f2012-06-24 17:37:07 +0200299
Georg Brandl116aa622007-08-15 14:28:22 +0000300.. exception:: Error
301
Éric Araujo14382dc2011-07-28 22:49:11 +0200302 This exception collects exceptions that are raised during a multi-file
303 operation. For :func:`copytree`, the exception argument is a list of 3-tuples
304 (*srcname*, *dstname*, *exception*).
Georg Brandl116aa622007-08-15 14:28:22 +0000305
Georg Brandl116aa622007-08-15 14:28:22 +0000306
Éric Araujof2fbb9c2012-01-16 16:55:55 +0100307.. _shutil-copytree-example:
Georg Brandl116aa622007-08-15 14:28:22 +0000308
Tarek Ziadé396fad72010-02-23 05:30:31 +0000309copytree example
Georg Brandl03b9ad02012-06-24 18:09:40 +0200310~~~~~~~~~~~~~~~~
Georg Brandl116aa622007-08-15 14:28:22 +0000311
312This example is the implementation of the :func:`copytree` function, described
313above, with the docstring omitted. It demonstrates many of the other functions
314provided by this module. ::
315
316 def copytree(src, dst, symlinks=False):
317 names = os.listdir(src)
318 os.makedirs(dst)
319 errors = []
320 for name in names:
321 srcname = os.path.join(src, name)
322 dstname = os.path.join(dst, name)
323 try:
324 if symlinks and os.path.islink(srcname):
325 linkto = os.readlink(srcname)
326 os.symlink(linkto, dstname)
327 elif os.path.isdir(srcname):
328 copytree(srcname, dstname, symlinks)
329 else:
330 copy2(srcname, dstname)
331 # XXX What about devices, sockets etc.?
332 except (IOError, os.error) as why:
333 errors.append((srcname, dstname, str(why)))
334 # catch the Error from the recursive copytree so that we can
335 # continue with other files
336 except Error as err:
337 errors.extend(err.args[0])
338 try:
339 copystat(src, dst)
340 except WindowsError:
341 # can't copy file access times on Windows
342 pass
343 except OSError as why:
344 errors.extend((src, dst, str(why)))
345 if errors:
Collin Winterc79461b2007-09-01 23:34:30 +0000346 raise Error(errors)
Georg Brandl116aa622007-08-15 14:28:22 +0000347
Tarek Ziadé396fad72010-02-23 05:30:31 +0000348Another example that uses the :func:`ignore_patterns` helper::
349
350 from shutil import copytree, ignore_patterns
351
352 copytree(source, destination, ignore=ignore_patterns('*.pyc', 'tmp*'))
353
354This will copy everything except ``.pyc`` files and files or directories whose
355name starts with ``tmp``.
356
357Another example that uses the *ignore* argument to add a logging call::
358
359 from shutil import copytree
360 import logging
361
362 def _logpath(path, names):
363 logging.info('Working in %s' % path)
364 return [] # nothing will be ignored
365
366 copytree(source, destination, ignore=_logpath)
367
368
Raymond Hettinger0929b1f2011-01-23 11:29:08 +0000369.. _archiving-operations:
370
371Archiving operations
372--------------------
Tarek Ziadé396fad72010-02-23 05:30:31 +0000373
Georg Brandl03b9ad02012-06-24 18:09:40 +0200374.. versionadded:: 3.2
375
Éric Araujof2fbb9c2012-01-16 16:55:55 +0100376High-level utilities to create and read compressed and archived files are also
377provided. They rely on the :mod:`zipfile` and :mod:`tarfile` modules.
378
Tarek Ziadé396fad72010-02-23 05:30:31 +0000379.. function:: make_archive(base_name, format, [root_dir, [base_dir, [verbose, [dry_run, [owner, [group, [logger]]]]]]])
380
Raymond Hettinger0929b1f2011-01-23 11:29:08 +0000381 Create an archive file (such as zip or tar) and return its name.
Tarek Ziadé396fad72010-02-23 05:30:31 +0000382
383 *base_name* is the name of the file to create, including the path, minus
384 any format-specific extension. *format* is the archive format: one of
Tarek Ziadéffa155a2010-04-29 13:34:35 +0000385 "zip", "tar", "bztar" (if the :mod:`bz2` module is available) or "gztar".
Tarek Ziadé396fad72010-02-23 05:30:31 +0000386
387 *root_dir* is a directory that will be the root directory of the
Raymond Hettinger0929b1f2011-01-23 11:29:08 +0000388 archive; for example, we typically chdir into *root_dir* before creating the
Tarek Ziadé396fad72010-02-23 05:30:31 +0000389 archive.
390
391 *base_dir* is the directory where we start archiving from;
Ezio Melotticb999a32010-04-20 11:26:51 +0000392 i.e. *base_dir* will be the common prefix of all files and
Tarek Ziadé396fad72010-02-23 05:30:31 +0000393 directories in the archive.
394
395 *root_dir* and *base_dir* both default to the current directory.
396
397 *owner* and *group* are used when creating a tar archive. By default,
398 uses the current owner and group.
399
Éric Araujo06c42a32011-11-07 17:31:07 +0100400 *logger* must be an object compatible with :pep:`282`, usually an instance of
401 :class:`logging.Logger`.
Raymond Hettinger0929b1f2011-01-23 11:29:08 +0000402
Tarek Ziadé396fad72010-02-23 05:30:31 +0000403
404.. function:: get_archive_formats()
405
Éric Araujo14382dc2011-07-28 22:49:11 +0200406 Return a list of supported formats for archiving.
Tarek Ziadé396fad72010-02-23 05:30:31 +0000407 Each element of the returned sequence is a tuple ``(name, description)``
408
409 By default :mod:`shutil` provides these formats:
410
411 - *gztar*: gzip'ed tar-file
Tarek Ziadéffa155a2010-04-29 13:34:35 +0000412 - *bztar*: bzip2'ed tar-file (if the :mod:`bz2` module is available.)
Tarek Ziadé396fad72010-02-23 05:30:31 +0000413 - *tar*: uncompressed tar file
414 - *zip*: ZIP file
415
416 You can register new formats or provide your own archiver for any existing
417 formats, by using :func:`register_archive_format`.
418
Tarek Ziadé396fad72010-02-23 05:30:31 +0000419
420.. function:: register_archive_format(name, function, [extra_args, [description]])
421
Éric Araujo14382dc2011-07-28 22:49:11 +0200422 Register an archiver for the format *name*. *function* is a callable that
Tarek Ziadé396fad72010-02-23 05:30:31 +0000423 will be used to invoke the archiver.
424
Raymond Hettinger0929b1f2011-01-23 11:29:08 +0000425 If given, *extra_args* is a sequence of ``(name, value)`` pairs that will be
Tarek Ziadé396fad72010-02-23 05:30:31 +0000426 used as extra keywords arguments when the archiver callable is used.
427
428 *description* is used by :func:`get_archive_formats` which returns the
429 list of archivers. Defaults to an empty list.
430
Tarek Ziadé396fad72010-02-23 05:30:31 +0000431
Tarek Ziadé6ac91722010-04-28 17:51:36 +0000432.. function:: unregister_archive_format(name)
Tarek Ziadé396fad72010-02-23 05:30:31 +0000433
434 Remove the archive format *name* from the list of supported formats.
435
Tarek Ziadé396fad72010-02-23 05:30:31 +0000436
Tarek Ziadé6ac91722010-04-28 17:51:36 +0000437.. function:: unpack_archive(filename[, extract_dir[, format]])
438
439 Unpack an archive. *filename* is the full path of the archive.
440
441 *extract_dir* is the name of the target directory where the archive is
442 unpacked. If not provided, the current working directory is used.
443
444 *format* is the archive format: one of "zip", "tar", or "gztar". Or any
445 other format registered with :func:`register_unpack_format`. If not
446 provided, :func:`unpack_archive` will use the archive file name extension
447 and see if an unpacker was registered for that extension. In case none is
448 found, a :exc:`ValueError` is raised.
449
Tarek Ziadé6ac91722010-04-28 17:51:36 +0000450
Raymond Hettinger0929b1f2011-01-23 11:29:08 +0000451.. function:: register_unpack_format(name, extensions, function[, extra_args[, description]])
Tarek Ziadé6ac91722010-04-28 17:51:36 +0000452
453 Registers an unpack format. *name* is the name of the format and
454 *extensions* is a list of extensions corresponding to the format, like
455 ``.zip`` for Zip files.
456
457 *function* is the callable that will be used to unpack archives. The
458 callable will receive the path of the archive, followed by the directory
459 the archive must be extracted to.
460
461 When provided, *extra_args* is a sequence of ``(name, value)`` tuples that
462 will be passed as keywords arguments to the callable.
463
464 *description* can be provided to describe the format, and will be returned
465 by the :func:`get_unpack_formats` function.
466
Tarek Ziadé6ac91722010-04-28 17:51:36 +0000467
468.. function:: unregister_unpack_format(name)
469
470 Unregister an unpack format. *name* is the name of the format.
471
Tarek Ziadé6ac91722010-04-28 17:51:36 +0000472
473.. function:: get_unpack_formats()
474
475 Return a list of all registered formats for unpacking.
476 Each element of the returned sequence is a tuple
477 ``(name, extensions, description)``.
478
479 By default :mod:`shutil` provides these formats:
480
481 - *gztar*: gzip'ed tar-file
Tarek Ziadéffa155a2010-04-29 13:34:35 +0000482 - *bztar*: bzip2'ed tar-file (if the :mod:`bz2` module is available.)
Tarek Ziadé6ac91722010-04-28 17:51:36 +0000483 - *tar*: uncompressed tar file
484 - *zip*: ZIP file
485
486 You can register new formats or provide your own unpacker for any existing
487 formats, by using :func:`register_unpack_format`.
488
Tarek Ziadé6ac91722010-04-28 17:51:36 +0000489
Éric Araujof2fbb9c2012-01-16 16:55:55 +0100490.. _shutil-archiving-example:
Tarek Ziadé6ac91722010-04-28 17:51:36 +0000491
Tarek Ziadé396fad72010-02-23 05:30:31 +0000492Archiving example
Georg Brandl03b9ad02012-06-24 18:09:40 +0200493~~~~~~~~~~~~~~~~~
Tarek Ziadé396fad72010-02-23 05:30:31 +0000494
495In this example, we create a gzip'ed tar-file archive containing all files
496found in the :file:`.ssh` directory of the user::
497
498 >>> from shutil import make_archive
499 >>> import os
500 >>> archive_name = os.path.expanduser(os.path.join('~', 'myarchive'))
501 >>> root_dir = os.path.expanduser(os.path.join('~', '.ssh'))
502 >>> make_archive(archive_name, 'gztar', root_dir)
503 '/Users/tarek/myarchive.tar.gz'
504
505The resulting archive contains::
506
507 $ tar -tzvf /Users/tarek/myarchive.tar.gz
508 drwx------ tarek/staff 0 2010-02-01 16:23:40 ./
509 -rw-r--r-- tarek/staff 609 2008-06-09 13:26:54 ./authorized_keys
510 -rwxr-xr-x tarek/staff 65 2008-06-09 13:26:54 ./config
511 -rwx------ tarek/staff 668 2008-06-09 13:26:54 ./id_dsa
512 -rwxr-xr-x tarek/staff 609 2008-06-09 13:26:54 ./id_dsa.pub
513 -rw------- tarek/staff 1675 2008-06-09 13:26:54 ./id_rsa
514 -rw-r--r-- tarek/staff 397 2008-06-09 13:26:54 ./id_rsa.pub
515 -rw-r--r-- tarek/staff 37192 2010-02-06 18:23:10 ./known_hosts
Antoine Pitroubcf2b592012-02-08 23:28:36 +0100516
517
518Querying the size of the output terminal
519----------------------------------------
520
521.. versionadded:: 3.3
522
523.. function:: get_terminal_size(fallback=(columns, lines))
524
525 Get the size of the terminal window.
526
527 For each of the two dimensions, the environment variable, ``COLUMNS``
528 and ``LINES`` respectively, is checked. If the variable is defined and
529 the value is a positive integer, it is used.
530
531 When ``COLUMNS`` or ``LINES`` is not defined, which is the common case,
532 the terminal connected to :data:`sys.__stdout__` is queried
533 by invoking :func:`os.get_terminal_size`.
534
535 If the terminal size cannot be successfully queried, either because
536 the system doesn't support querying, or because we are not
537 connected to a terminal, the value given in ``fallback`` parameter
538 is used. ``fallback`` defaults to ``(80, 24)`` which is the default
539 size used by many terminal emulators.
540
541 The value returned is a named tuple of type :class:`os.terminal_size`.
542
543 See also: The Single UNIX Specification, Version 2,
544 `Other Environment Variables`_.
545
546.. _`Other Environment Variables`:
547 http://pubs.opengroup.org/onlinepubs/7908799/xbd/envvar.html#tag_002_003
548