blob: 5521841347e0001371b5d52686ab53f938c3e340 [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
Hynek Schlawack6e49ac22012-05-21 13:41:25 +020050.. function:: copyfile(src, dst, symlinks=False)
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
55 *src* and *dst* are the same files, :exc:`Error` is raised.
Senthil Kumaran1fd64822012-02-13 23:35:44 +080056
Antoine Pitrou62ab10a02011-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
Antoine Pitrou78091e62011-12-29 18:54:15 +010062 If *symlinks* is true and *src* is a symbolic link, a new symbolic link will
63 be created instead of copying the file *src* points to.
64
Antoine Pitrou62ab10a02011-10-12 20:10:51 +020065 .. versionchanged:: 3.3
66 :exc:`IOError` used to be raised instead of :exc:`OSError`.
Antoine Pitrou78091e62011-12-29 18:54:15 +010067 Added *symlinks* argument.
Antoine Pitrou62ab10a02011-10-12 20:10:51 +020068
Brian Curtin066dacf2012-06-19 10:03:05 -050069 .. versionchanged:: 3.3
70 Added return of the *dst*.
Christian Heimesa342c012008-04-20 21:01:16 +000071
Hynek Schlawack6e49ac22012-05-21 13:41:25 +020072.. function:: copymode(src, dst, symlinks=False)
Georg Brandl116aa622007-08-15 14:28:22 +000073
74 Copy the permission bits from *src* to *dst*. The file contents, owner, and
Antoine Pitrou78091e62011-12-29 18:54:15 +010075 group are unaffected. *src* and *dst* are path names given as strings. If
76 *symlinks* is true, *src* a symbolic link and the operating system supports
77 modes for symbolic links (for example BSD-based ones), the mode of the link
78 will be copied.
Georg Brandl116aa622007-08-15 14:28:22 +000079
Antoine Pitrou78091e62011-12-29 18:54:15 +010080 .. versionchanged:: 3.3
81 Added *symlinks* argument.
Georg Brandl116aa622007-08-15 14:28:22 +000082
Hynek Schlawack6e49ac22012-05-21 13:41:25 +020083.. function:: copystat(src, dst, symlinks=False)
Georg Brandl116aa622007-08-15 14:28:22 +000084
85 Copy the permission bits, last access time, last modification time, and flags
86 from *src* to *dst*. The file contents, owner, and group are unaffected. *src*
Antoine Pitrou78091e62011-12-29 18:54:15 +010087 and *dst* are path names given as strings. If *src* and *dst* are both
88 symbolic links and *symlinks* true, the stats of the link will be copied as
89 far as the platform allows.
Georg Brandl116aa622007-08-15 14:28:22 +000090
Antoine Pitrou78091e62011-12-29 18:54:15 +010091 .. versionchanged:: 3.3
92 Added *symlinks* argument.
Georg Brandl116aa622007-08-15 14:28:22 +000093
Hynek Schlawack6e49ac22012-05-21 13:41:25 +020094.. function:: copy(src, dst, symlinks=False))
Georg Brandl116aa622007-08-15 14:28:22 +000095
Brian Curtin0d0a1de2012-06-18 18:41:07 -050096 Copy the file *src* to the file or directory *dst* and return the file's
97 destination. If *dst* is a directory, a
Georg Brandl116aa622007-08-15 14:28:22 +000098 file with the same basename as *src* is created (or overwritten) in the
99 directory specified. Permission bits are copied. *src* and *dst* are path
Antoine Pitrou78091e62011-12-29 18:54:15 +0100100 names given as strings. If *symlinks* is true, symbolic links won't be
101 followed but recreated instead -- this resembles GNU's :program:`cp -P`.
Georg Brandl116aa622007-08-15 14:28:22 +0000102
Antoine Pitrou78091e62011-12-29 18:54:15 +0100103 .. versionchanged:: 3.3
104 Added *symlinks* argument.
Georg Brandl116aa622007-08-15 14:28:22 +0000105
Brian Curtin066dacf2012-06-19 10:03:05 -0500106 .. versionchanged:: 3.3
107 Added return of the *dst*.
108
Hynek Schlawack6e49ac22012-05-21 13:41:25 +0200109.. function:: copy2(src, dst, symlinks=False)
Georg Brandl116aa622007-08-15 14:28:22 +0000110
Brian Curtin0d0a1de2012-06-18 18:41:07 -0500111 Similar to :func:`shutil.copy`, including that the destination is
112 returned, but metadata is copied as well. This is
Senthil Kumaran1fd64822012-02-13 23:35:44 +0800113 similar to the Unix command :program:`cp -p`. If *symlinks* is true,
114 symbolic links won't be followed but recreated instead -- this resembles
115 GNU's :program:`cp -P`.
Georg Brandl116aa622007-08-15 14:28:22 +0000116
Antoine Pitrou78091e62011-12-29 18:54:15 +0100117 .. versionchanged:: 3.3
Antoine Pitrou424246f2012-05-12 19:02:01 +0200118 Added *symlinks* argument, try to copy extended file system attributes
119 too (currently Linux only).
Georg Brandl116aa622007-08-15 14:28:22 +0000120
Brian Curtin066dacf2012-06-19 10:03:05 -0500121 .. versionchanged:: 3.3
122 Added return of the *dst*.
123
Georg Brandl86b2fb92008-07-16 03:43:04 +0000124.. function:: ignore_patterns(\*patterns)
125
126 This factory function creates a function that can be used as a callable for
127 :func:`copytree`\'s *ignore* argument, ignoring files and directories that
128 match one of the glob-style *patterns* provided. See the example below.
129
130
Ezio Melotticb999a32010-04-20 11:26:51 +0000131.. function:: copytree(src, dst, symlinks=False, ignore=None, copy_function=copy2, ignore_dangling_symlinks=False)
Georg Brandl116aa622007-08-15 14:28:22 +0000132
Brian Curtin0d0a1de2012-06-18 18:41:07 -0500133 Recursively copy an entire directory tree rooted at *src*, returning the
134 destination directory. The destination
Senthil Kumaran7f728c12012-02-13 23:30:47 +0800135 directory, named by *dst*, must not already exist; it will be created as
136 well as missing parent directories. Permissions and times of directories
137 are copied with :func:`copystat`, individual files are copied using
138 :func:`shutil.copy2`.
Georg Brandl116aa622007-08-15 14:28:22 +0000139
Georg Brandl86b2fb92008-07-16 03:43:04 +0000140 If *symlinks* is true, symbolic links in the source tree are represented as
Antoine Pitrou78091e62011-12-29 18:54:15 +0100141 symbolic links in the new tree and the metadata of the original links will
142 be copied as far as the platform allows; if false or omitted, the contents
143 and metadata of the linked files are copied to the new tree.
Georg Brandl86b2fb92008-07-16 03:43:04 +0000144
Tarek Ziadéfb437512010-04-20 08:57:33 +0000145 When *symlinks* is false, if the file pointed by the symlink doesn't
146 exist, a exception will be added in the list of errors raised in
147 a :exc:`Error` exception at the end of the copy process.
148 You can set the optional *ignore_dangling_symlinks* flag to true if you
Tarek Ziadé8c26c7d2010-04-23 13:03:50 +0000149 want to silence this exception. Notice that this option has no effect
150 on platforms that don't support :func:`os.symlink`.
Tarek Ziadéfb437512010-04-20 08:57:33 +0000151
Georg Brandl86b2fb92008-07-16 03:43:04 +0000152 If *ignore* is given, it must be a callable that will receive as its
153 arguments the directory being visited by :func:`copytree`, and a list of its
154 contents, as returned by :func:`os.listdir`. Since :func:`copytree` is
155 called recursively, the *ignore* callable will be called once for each
156 directory that is copied. The callable must return a sequence of directory
157 and file names relative to the current directory (i.e. a subset of the items
158 in its second argument); these names will then be ignored in the copy
159 process. :func:`ignore_patterns` can be used to create such a callable that
160 ignores names based on glob-style patterns.
161
162 If exception(s) occur, an :exc:`Error` is raised with a list of reasons.
163
Senthil Kumaran7f728c12012-02-13 23:30:47 +0800164 If *copy_function* is given, it must be a callable that will be used to copy
165 each file. It will be called with the source path and the destination path
166 as arguments. By default, :func:`shutil.copy2` is used, but any function
Senthil Kumaran1fd64822012-02-13 23:35:44 +0800167 that supports the same signature (like :func:`shutil.copy`) can be used.
Georg Brandl116aa622007-08-15 14:28:22 +0000168
Tarek Ziadé5340db32010-04-19 22:30:51 +0000169 .. versionchanged:: 3.2
170 Added the *copy_function* argument to be able to provide a custom copy
171 function.
Georg Brandl116aa622007-08-15 14:28:22 +0000172
Ezio Melotticb999a32010-04-20 11:26:51 +0000173 .. versionchanged:: 3.2
Tarek Ziadéfb437512010-04-20 08:57:33 +0000174 Added the *ignore_dangling_symlinks* argument to silent dangling symlinks
175 errors when *symlinks* is false.
176
Antoine Pitrou78091e62011-12-29 18:54:15 +0100177 .. versionchanged:: 3.3
178 Copy metadata when *symlinks* is false.
179
Brian Curtin066dacf2012-06-19 10:03:05 -0500180 .. versionchanged:: 3.3
181 Added return of the *dst*.
Tarek Ziadéfb437512010-04-20 08:57:33 +0000182
Georg Brandl18244152009-09-02 20:34:52 +0000183.. function:: rmtree(path, ignore_errors=False, onerror=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000184
185 .. index:: single: directory; deleting
186
Christian Heimes9bd667a2008-01-20 15:14:11 +0000187 Delete an entire directory tree; *path* must point to a directory (but not a
188 symbolic link to a directory). If *ignore_errors* is true, errors resulting
189 from failed removals will be ignored; if false or omitted, such errors are
190 handled by calling a handler specified by *onerror* or, if that is omitted,
191 they raise an exception.
Georg Brandl116aa622007-08-15 14:28:22 +0000192
Hynek Schlawack67be92b2012-06-23 17:58:42 +0200193 .. warning::
194
195 The default :func:`rmtree` function is susceptible to a symlink attack:
196 given proper timing and circumstances, attackers can use it to delete
197 files they wouldn't be able to access otherwise. Thus -- on platforms
Hynek Schlawack2100b422012-06-23 20:28:32 +0200198 that support the necessary fd-based functions -- a safe version of
199 :func:`rmtree` is used, which isn't vulnerable. In this case
200 :data:`rmtree_is_safe` is set to True.
Hynek Schlawack67be92b2012-06-23 17:58:42 +0200201
Christian Heimes9bd667a2008-01-20 15:14:11 +0000202 If *onerror* is provided, it must be a callable that accepts three
Hynek Schlawack67be92b2012-06-23 17:58:42 +0200203 parameters: *function*, *path*, and *excinfo*.
204
205 The first parameter, *function*, is the function which raised the exception;
206 it depends on the platform and implementation. The second parameter,
207 *path*, will be the path name passed to *function*. The third parameter,
208 *excinfo*, will be the exception information returned by
209 :func:`sys.exc_info`. Exceptions raised by *onerror* will not be caught.
210
211 .. versionchanged:: 3.3
212 Added a safe version that is used automatically if platform supports
Hynek Schlawack2100b422012-06-23 20:28:32 +0200213 fd-based functions.
Christian Heimes9bd667a2008-01-20 15:14:11 +0000214
Hynek Schlawack2100b422012-06-23 20:28:32 +0200215.. data:: rmtree_is_safe
216
217 Indicates whether the current platform and implementation has a symlink
218 attack-proof version of :func:`rmtree`. Currently this is only true for
219 platforms supporting fd-based directory access functions.
220
221 .. versionadded:: 3.3
Georg Brandl116aa622007-08-15 14:28:22 +0000222
223.. function:: move(src, dst)
224
Brian Curtin0d0a1de2012-06-18 18:41:07 -0500225 Recursively move a file or directory (*src*) to another location (*dst*)
226 and return the destination.
Georg Brandl116aa622007-08-15 14:28:22 +0000227
Éric Araujo14382dc2011-07-28 22:49:11 +0200228 If the destination is a directory or a symlink to a directory, then *src* is
229 moved inside that directory.
230
231 The destination directory must not already exist. If the destination already
232 exists but is not a directory, it may be overwritten depending on
233 :func:`os.rename` semantics.
234
235 If the destination is on the current filesystem, then :func:`os.rename` is
Senthil Kumaran7f728c12012-02-13 23:30:47 +0800236 used. Otherwise, *src* is copied (using :func:`shutil.copy2`) to *dst* and
Senthil Kumaran1fd64822012-02-13 23:35:44 +0800237 then removed. In case of symlinks, a new symlink pointing to the target of
238 *src* will be created in or as *dst* and *src* will be removed.
Antoine Pitrou0a08d7a2012-01-06 20:16:19 +0100239
240 .. versionchanged:: 3.3
241 Added explicit symlink handling for foreign filesystems, thus adapting
242 it to the behavior of GNU's :program:`mv`.
Georg Brandl116aa622007-08-15 14:28:22 +0000243
Brian Curtin066dacf2012-06-19 10:03:05 -0500244 .. versionchanged:: 3.3
245 Added return of the *dst*.
246
Giampaolo Rodola'210e7ca2011-07-01 13:55:36 +0200247.. function:: disk_usage(path)
248
Éric Araujoe4d5b8e2011-08-08 16:51:11 +0200249 Return disk usage statistics about the given path as a :term:`named tuple`
250 with the attributes *total*, *used* and *free*, which are the amount of
251 total, used and free space, in bytes.
Giampaolo Rodola'210e7ca2011-07-01 13:55:36 +0200252
253 .. versionadded:: 3.3
254
255 Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000256
Sandro Tosid902a142011-08-22 23:28:27 +0200257.. function:: chown(path, user=None, group=None)
258
259 Change owner *user* and/or *group* of the given *path*.
260
261 *user* can be a system user name or a uid; the same applies to *group*. At
262 least one argument is required.
263
264 See also :func:`os.chown`, the underlying function.
265
266 Availability: Unix.
267
268 .. versionadded:: 3.3
269
Brian Curtinc57a3452012-06-22 16:00:30 -0500270.. function:: which(cmd, mode=os.F_OK | os.X_OK, path=None)
271
Antoine Pitrou07c24d12012-06-22 23:33:05 +0200272 Return the path to an executable which would be run if the given *cmd*
273 was called. If no *cmd* would be called, return ``None``.
Brian Curtinc57a3452012-06-22 16:00:30 -0500274
275 *mode* is a permission mask passed a to :func:`os.access`, by default
276 determining if the file exists and executable.
277
278 When no *path* is specified, the results of :func:`os.environ` are
279 used, returning either the "PATH" value or a fallback of :attr:`os.defpath`.
280
281 On Windows, the current directory is always prepended to the *path*
282 whether or not you use the default or provide your own, which
283 is the behavior the command shell uses when finding executables.
284 Additionaly, when finding the *cmd* in the *path*, the
285 ``PATHEXT`` environment variable is checked. For example, if you
286 call ``shutil.which("python")``, :func:`which` will search
287 ``PATHEXT`` to know that it should look for ``python.exe`` within
288 the *path* directories.
289
290 >>> print(shutil.which("python"))
291 'c:\\python33\\python.exe'
292
293 .. versionadded:: 3.3
Sandro Tosid902a142011-08-22 23:28:27 +0200294
Georg Brandl116aa622007-08-15 14:28:22 +0000295.. exception:: Error
296
Éric Araujo14382dc2011-07-28 22:49:11 +0200297 This exception collects exceptions that are raised during a multi-file
298 operation. For :func:`copytree`, the exception argument is a list of 3-tuples
299 (*srcname*, *dstname*, *exception*).
Georg Brandl116aa622007-08-15 14:28:22 +0000300
Georg Brandl116aa622007-08-15 14:28:22 +0000301
Éric Araujof2fbb9c2012-01-16 16:55:55 +0100302.. _shutil-copytree-example:
Georg Brandl116aa622007-08-15 14:28:22 +0000303
Tarek Ziadé396fad72010-02-23 05:30:31 +0000304copytree example
305::::::::::::::::
Georg Brandl116aa622007-08-15 14:28:22 +0000306
307This example is the implementation of the :func:`copytree` function, described
308above, with the docstring omitted. It demonstrates many of the other functions
309provided by this module. ::
310
311 def copytree(src, dst, symlinks=False):
312 names = os.listdir(src)
313 os.makedirs(dst)
314 errors = []
315 for name in names:
316 srcname = os.path.join(src, name)
317 dstname = os.path.join(dst, name)
318 try:
319 if symlinks and os.path.islink(srcname):
320 linkto = os.readlink(srcname)
321 os.symlink(linkto, dstname)
322 elif os.path.isdir(srcname):
323 copytree(srcname, dstname, symlinks)
324 else:
325 copy2(srcname, dstname)
326 # XXX What about devices, sockets etc.?
327 except (IOError, os.error) as why:
328 errors.append((srcname, dstname, str(why)))
329 # catch the Error from the recursive copytree so that we can
330 # continue with other files
331 except Error as err:
332 errors.extend(err.args[0])
333 try:
334 copystat(src, dst)
335 except WindowsError:
336 # can't copy file access times on Windows
337 pass
338 except OSError as why:
339 errors.extend((src, dst, str(why)))
340 if errors:
Collin Winterc79461b2007-09-01 23:34:30 +0000341 raise Error(errors)
Georg Brandl116aa622007-08-15 14:28:22 +0000342
Tarek Ziadé396fad72010-02-23 05:30:31 +0000343Another example that uses the :func:`ignore_patterns` helper::
344
345 from shutil import copytree, ignore_patterns
346
347 copytree(source, destination, ignore=ignore_patterns('*.pyc', 'tmp*'))
348
349This will copy everything except ``.pyc`` files and files or directories whose
350name starts with ``tmp``.
351
352Another example that uses the *ignore* argument to add a logging call::
353
354 from shutil import copytree
355 import logging
356
357 def _logpath(path, names):
358 logging.info('Working in %s' % path)
359 return [] # nothing will be ignored
360
361 copytree(source, destination, ignore=_logpath)
362
363
Raymond Hettinger0929b1f2011-01-23 11:29:08 +0000364.. _archiving-operations:
365
366Archiving operations
367--------------------
Tarek Ziadé396fad72010-02-23 05:30:31 +0000368
Éric Araujof2fbb9c2012-01-16 16:55:55 +0100369High-level utilities to create and read compressed and archived files are also
370provided. They rely on the :mod:`zipfile` and :mod:`tarfile` modules.
371
Tarek Ziadé396fad72010-02-23 05:30:31 +0000372.. function:: make_archive(base_name, format, [root_dir, [base_dir, [verbose, [dry_run, [owner, [group, [logger]]]]]]])
373
Raymond Hettinger0929b1f2011-01-23 11:29:08 +0000374 Create an archive file (such as zip or tar) and return its name.
Tarek Ziadé396fad72010-02-23 05:30:31 +0000375
376 *base_name* is the name of the file to create, including the path, minus
377 any format-specific extension. *format* is the archive format: one of
Tarek Ziadéffa155a2010-04-29 13:34:35 +0000378 "zip", "tar", "bztar" (if the :mod:`bz2` module is available) or "gztar".
Tarek Ziadé396fad72010-02-23 05:30:31 +0000379
380 *root_dir* is a directory that will be the root directory of the
Raymond Hettinger0929b1f2011-01-23 11:29:08 +0000381 archive; for example, we typically chdir into *root_dir* before creating the
Tarek Ziadé396fad72010-02-23 05:30:31 +0000382 archive.
383
384 *base_dir* is the directory where we start archiving from;
Ezio Melotticb999a32010-04-20 11:26:51 +0000385 i.e. *base_dir* will be the common prefix of all files and
Tarek Ziadé396fad72010-02-23 05:30:31 +0000386 directories in the archive.
387
388 *root_dir* and *base_dir* both default to the current directory.
389
390 *owner* and *group* are used when creating a tar archive. By default,
391 uses the current owner and group.
392
Éric Araujo06c42a32011-11-07 17:31:07 +0100393 *logger* must be an object compatible with :pep:`282`, usually an instance of
394 :class:`logging.Logger`.
Raymond Hettinger0929b1f2011-01-23 11:29:08 +0000395
Ezio Melottif8754a62010-03-21 07:16:43 +0000396 .. versionadded:: 3.2
Tarek Ziadé396fad72010-02-23 05:30:31 +0000397
398
399.. function:: get_archive_formats()
400
Éric Araujo14382dc2011-07-28 22:49:11 +0200401 Return a list of supported formats for archiving.
Tarek Ziadé396fad72010-02-23 05:30:31 +0000402 Each element of the returned sequence is a tuple ``(name, description)``
403
404 By default :mod:`shutil` provides these formats:
405
406 - *gztar*: gzip'ed tar-file
Tarek Ziadéffa155a2010-04-29 13:34:35 +0000407 - *bztar*: bzip2'ed tar-file (if the :mod:`bz2` module is available.)
Tarek Ziadé396fad72010-02-23 05:30:31 +0000408 - *tar*: uncompressed tar file
409 - *zip*: ZIP file
410
411 You can register new formats or provide your own archiver for any existing
412 formats, by using :func:`register_archive_format`.
413
Ezio Melottif8754a62010-03-21 07:16:43 +0000414 .. versionadded:: 3.2
Tarek Ziadé396fad72010-02-23 05:30:31 +0000415
416
417.. function:: register_archive_format(name, function, [extra_args, [description]])
418
Éric Araujo14382dc2011-07-28 22:49:11 +0200419 Register an archiver for the format *name*. *function* is a callable that
Tarek Ziadé396fad72010-02-23 05:30:31 +0000420 will be used to invoke the archiver.
421
Raymond Hettinger0929b1f2011-01-23 11:29:08 +0000422 If given, *extra_args* is a sequence of ``(name, value)`` pairs that will be
Tarek Ziadé396fad72010-02-23 05:30:31 +0000423 used as extra keywords arguments when the archiver callable is used.
424
425 *description* is used by :func:`get_archive_formats` which returns the
426 list of archivers. Defaults to an empty list.
427
Ezio Melottif8754a62010-03-21 07:16:43 +0000428 .. versionadded:: 3.2
Tarek Ziadé396fad72010-02-23 05:30:31 +0000429
430
Tarek Ziadé6ac91722010-04-28 17:51:36 +0000431.. function:: unregister_archive_format(name)
Tarek Ziadé396fad72010-02-23 05:30:31 +0000432
433 Remove the archive format *name* from the list of supported formats.
434
Ezio Melottif8754a62010-03-21 07:16:43 +0000435 .. versionadded:: 3.2
Tarek Ziadé396fad72010-02-23 05:30:31 +0000436
437
Tarek Ziadé6ac91722010-04-28 17:51:36 +0000438.. function:: unpack_archive(filename[, extract_dir[, format]])
439
440 Unpack an archive. *filename* is the full path of the archive.
441
442 *extract_dir* is the name of the target directory where the archive is
443 unpacked. If not provided, the current working directory is used.
444
445 *format* is the archive format: one of "zip", "tar", or "gztar". Or any
446 other format registered with :func:`register_unpack_format`. If not
447 provided, :func:`unpack_archive` will use the archive file name extension
448 and see if an unpacker was registered for that extension. In case none is
449 found, a :exc:`ValueError` is raised.
450
451 .. versionadded:: 3.2
452
453
Raymond Hettinger0929b1f2011-01-23 11:29:08 +0000454.. function:: register_unpack_format(name, extensions, function[, extra_args[, description]])
Tarek Ziadé6ac91722010-04-28 17:51:36 +0000455
456 Registers an unpack format. *name* is the name of the format and
457 *extensions* is a list of extensions corresponding to the format, like
458 ``.zip`` for Zip files.
459
460 *function* is the callable that will be used to unpack archives. The
461 callable will receive the path of the archive, followed by the directory
462 the archive must be extracted to.
463
464 When provided, *extra_args* is a sequence of ``(name, value)`` tuples that
465 will be passed as keywords arguments to the callable.
466
467 *description* can be provided to describe the format, and will be returned
468 by the :func:`get_unpack_formats` function.
469
470 .. versionadded:: 3.2
471
472
473.. function:: unregister_unpack_format(name)
474
475 Unregister an unpack format. *name* is the name of the format.
476
477 .. versionadded:: 3.2
478
479
480.. function:: get_unpack_formats()
481
482 Return a list of all registered formats for unpacking.
483 Each element of the returned sequence is a tuple
484 ``(name, extensions, description)``.
485
486 By default :mod:`shutil` provides these formats:
487
488 - *gztar*: gzip'ed tar-file
Tarek Ziadéffa155a2010-04-29 13:34:35 +0000489 - *bztar*: bzip2'ed tar-file (if the :mod:`bz2` module is available.)
Tarek Ziadé6ac91722010-04-28 17:51:36 +0000490 - *tar*: uncompressed tar file
491 - *zip*: ZIP file
492
493 You can register new formats or provide your own unpacker for any existing
494 formats, by using :func:`register_unpack_format`.
495
496 .. versionadded:: 3.2
497
498
Éric Araujof2fbb9c2012-01-16 16:55:55 +0100499.. _shutil-archiving-example:
Tarek Ziadé6ac91722010-04-28 17:51:36 +0000500
Tarek Ziadé396fad72010-02-23 05:30:31 +0000501Archiving example
502:::::::::::::::::
503
504In this example, we create a gzip'ed tar-file archive containing all files
505found in the :file:`.ssh` directory of the user::
506
507 >>> from shutil import make_archive
508 >>> import os
509 >>> archive_name = os.path.expanduser(os.path.join('~', 'myarchive'))
510 >>> root_dir = os.path.expanduser(os.path.join('~', '.ssh'))
511 >>> make_archive(archive_name, 'gztar', root_dir)
512 '/Users/tarek/myarchive.tar.gz'
513
514The resulting archive contains::
515
516 $ tar -tzvf /Users/tarek/myarchive.tar.gz
517 drwx------ tarek/staff 0 2010-02-01 16:23:40 ./
518 -rw-r--r-- tarek/staff 609 2008-06-09 13:26:54 ./authorized_keys
519 -rwxr-xr-x tarek/staff 65 2008-06-09 13:26:54 ./config
520 -rwx------ tarek/staff 668 2008-06-09 13:26:54 ./id_dsa
521 -rwxr-xr-x tarek/staff 609 2008-06-09 13:26:54 ./id_dsa.pub
522 -rw------- tarek/staff 1675 2008-06-09 13:26:54 ./id_rsa
523 -rw-r--r-- tarek/staff 397 2008-06-09 13:26:54 ./id_rsa.pub
524 -rw-r--r-- tarek/staff 37192 2010-02-06 18:23:10 ./known_hosts
Antoine Pitroubcf2b592012-02-08 23:28:36 +0100525
526
527Querying the size of the output terminal
528----------------------------------------
529
530.. versionadded:: 3.3
531
532.. function:: get_terminal_size(fallback=(columns, lines))
533
534 Get the size of the terminal window.
535
536 For each of the two dimensions, the environment variable, ``COLUMNS``
537 and ``LINES`` respectively, is checked. If the variable is defined and
538 the value is a positive integer, it is used.
539
540 When ``COLUMNS`` or ``LINES`` is not defined, which is the common case,
541 the terminal connected to :data:`sys.__stdout__` is queried
542 by invoking :func:`os.get_terminal_size`.
543
544 If the terminal size cannot be successfully queried, either because
545 the system doesn't support querying, or because we are not
546 connected to a terminal, the value given in ``fallback`` parameter
547 is used. ``fallback`` defaults to ``(80, 24)`` which is the default
548 size used by many terminal emulators.
549
550 The value returned is a named tuple of type :class:`os.terminal_size`.
551
552 See also: The Single UNIX Specification, Version 2,
553 `Other Environment Variables`_.
554
555.. _`Other Environment Variables`:
556 http://pubs.opengroup.org/onlinepubs/7908799/xbd/envvar.html#tag_002_003
557