blob: bae7db8e3777b1357d60e39c65621fd6a983df40 [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
24 Even the higher-level file copying functions (:func:`copy`, :func:`copy2`)
Raymond Hettinger10480942011-01-10 03:26:08 +000025 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
Antoine Pitrou78091e62011-12-29 18:54:15 +010050.. function:: copyfile(src, dst[, symlinks=False])
Christian Heimesa342c012008-04-20 21:01:16 +000051
52 Copy the contents (no metadata) of the file named *src* to a file named *dst*.
53 *dst* must be the complete target file name; look at :func:`copy` for a copy that
Georg Brandlaf265f42008-12-07 15:06:20 +000054 accepts a target directory path. If *src* and *dst* are the same files,
55 :exc:`Error` is raised.
Antoine Pitrou62ab10a2011-10-12 20:10:51 +020056 The destination location must be writable; otherwise, an :exc:`OSError` exception
Christian Heimesa342c012008-04-20 21:01:16 +000057 will be raised. If *dst* already exists, it will be replaced. Special files
58 such as character or block devices and pipes cannot be copied with this
59 function. *src* and *dst* are path names given as strings.
60
Antoine Pitrou78091e62011-12-29 18:54:15 +010061 If *symlinks* is true and *src* is a symbolic link, a new symbolic link will
62 be created instead of copying the file *src* points to.
63
Antoine Pitrou62ab10a2011-10-12 20:10:51 +020064 .. versionchanged:: 3.3
65 :exc:`IOError` used to be raised instead of :exc:`OSError`.
Antoine Pitrou78091e62011-12-29 18:54:15 +010066 Added *symlinks* argument.
Antoine Pitrou62ab10a2011-10-12 20:10:51 +020067
Christian Heimesa342c012008-04-20 21:01:16 +000068
Antoine Pitrou78091e62011-12-29 18:54:15 +010069.. function:: copymode(src, dst[, symlinks=False])
Georg Brandl116aa622007-08-15 14:28:22 +000070
71 Copy the permission bits from *src* to *dst*. The file contents, owner, and
Antoine Pitrou78091e62011-12-29 18:54:15 +010072 group are unaffected. *src* and *dst* are path names given as strings. If
73 *symlinks* is true, *src* a symbolic link and the operating system supports
74 modes for symbolic links (for example BSD-based ones), the mode of the link
75 will be copied.
Georg Brandl116aa622007-08-15 14:28:22 +000076
Antoine Pitrou78091e62011-12-29 18:54:15 +010077 .. versionchanged:: 3.3
78 Added *symlinks* argument.
Georg Brandl116aa622007-08-15 14:28:22 +000079
Antoine Pitrou78091e62011-12-29 18:54:15 +010080.. function:: copystat(src, dst[, symlinks=False])
Georg Brandl116aa622007-08-15 14:28:22 +000081
82 Copy the permission bits, last access time, last modification time, and flags
83 from *src* to *dst*. The file contents, owner, and group are unaffected. *src*
Antoine Pitrou78091e62011-12-29 18:54:15 +010084 and *dst* are path names given as strings. If *src* and *dst* are both
85 symbolic links and *symlinks* true, the stats of the link will be copied as
86 far as the platform allows.
Georg Brandl116aa622007-08-15 14:28:22 +000087
Antoine Pitrou78091e62011-12-29 18:54:15 +010088 .. versionchanged:: 3.3
89 Added *symlinks* argument.
Georg Brandl116aa622007-08-15 14:28:22 +000090
Antoine Pitrou78091e62011-12-29 18:54:15 +010091.. function:: copy(src, dst[, symlinks=False]))
Georg Brandl116aa622007-08-15 14:28:22 +000092
93 Copy the file *src* to the file or directory *dst*. If *dst* is a directory, a
94 file with the same basename as *src* is created (or overwritten) in the
95 directory specified. Permission bits are copied. *src* and *dst* are path
Antoine Pitrou78091e62011-12-29 18:54:15 +010096 names given as strings. If *symlinks* is true, symbolic links won't be
97 followed but recreated instead -- this resembles GNU's :program:`cp -P`.
Georg Brandl116aa622007-08-15 14:28:22 +000098
Antoine Pitrou78091e62011-12-29 18:54:15 +010099 .. versionchanged:: 3.3
100 Added *symlinks* argument.
Georg Brandl116aa622007-08-15 14:28:22 +0000101
Antoine Pitrou78091e62011-12-29 18:54:15 +0100102.. function:: copy2(src, dst[, symlinks=False])
Georg Brandl116aa622007-08-15 14:28:22 +0000103
Alexandre Vassalottibee32532008-05-16 18:15:12 +0000104 Similar to :func:`copy`, but metadata is copied as well -- in fact, this is just
105 :func:`copy` followed by :func:`copystat`. This is similar to the
Antoine Pitrou78091e62011-12-29 18:54:15 +0100106 Unix command :program:`cp -p`. If *symlinks* is true, symbolic links won't
107 be followed but recreated instead -- this resembles GNU's :program:`cp -P`.
Georg Brandl116aa622007-08-15 14:28:22 +0000108
Antoine Pitrou78091e62011-12-29 18:54:15 +0100109 .. versionchanged:: 3.3
110 Added *symlinks* argument.
Georg Brandl116aa622007-08-15 14:28:22 +0000111
Georg Brandl86b2fb92008-07-16 03:43:04 +0000112.. function:: ignore_patterns(\*patterns)
113
114 This factory function creates a function that can be used as a callable for
115 :func:`copytree`\'s *ignore* argument, ignoring files and directories that
116 match one of the glob-style *patterns* provided. See the example below.
117
118
Ezio Melotticb999a32010-04-20 11:26:51 +0000119.. function:: copytree(src, dst, symlinks=False, ignore=None, copy_function=copy2, ignore_dangling_symlinks=False)
Georg Brandl116aa622007-08-15 14:28:22 +0000120
121 Recursively copy an entire directory tree rooted at *src*. The destination
Georg Brandl86b2fb92008-07-16 03:43:04 +0000122 directory, named by *dst*, must not already exist; it will be created as well
123 as missing parent directories. Permissions and times of directories are
124 copied with :func:`copystat`, individual files are copied using
125 :func:`copy2`.
Georg Brandl116aa622007-08-15 14:28:22 +0000126
Georg Brandl86b2fb92008-07-16 03:43:04 +0000127 If *symlinks* is true, symbolic links in the source tree are represented as
Antoine Pitrou78091e62011-12-29 18:54:15 +0100128 symbolic links in the new tree and the metadata of the original links will
129 be copied as far as the platform allows; if false or omitted, the contents
130 and metadata of the linked files are copied to the new tree.
Georg Brandl86b2fb92008-07-16 03:43:04 +0000131
Tarek Ziadéfb437512010-04-20 08:57:33 +0000132 When *symlinks* is false, if the file pointed by the symlink doesn't
133 exist, a exception will be added in the list of errors raised in
134 a :exc:`Error` exception at the end of the copy process.
135 You can set the optional *ignore_dangling_symlinks* flag to true if you
Tarek Ziadé8c26c7d2010-04-23 13:03:50 +0000136 want to silence this exception. Notice that this option has no effect
137 on platforms that don't support :func:`os.symlink`.
Tarek Ziadéfb437512010-04-20 08:57:33 +0000138
Georg Brandl86b2fb92008-07-16 03:43:04 +0000139 If *ignore* is given, it must be a callable that will receive as its
140 arguments the directory being visited by :func:`copytree`, and a list of its
141 contents, as returned by :func:`os.listdir`. Since :func:`copytree` is
142 called recursively, the *ignore* callable will be called once for each
143 directory that is copied. The callable must return a sequence of directory
144 and file names relative to the current directory (i.e. a subset of the items
145 in its second argument); these names will then be ignored in the copy
146 process. :func:`ignore_patterns` can be used to create such a callable that
147 ignores names based on glob-style patterns.
148
149 If exception(s) occur, an :exc:`Error` is raised with a list of reasons.
150
Tarek Ziadé5340db32010-04-19 22:30:51 +0000151 If *copy_function* is given, it must be a callable that will be used
152 to copy each file. It will be called with the source path and the
153 destination path as arguments. By default, :func:`copy2` is used, but any
154 function that supports the same signature (like :func:`copy`) can be used.
Georg Brandl116aa622007-08-15 14:28:22 +0000155
Tarek Ziadé5340db32010-04-19 22:30:51 +0000156 .. versionchanged:: 3.2
157 Added the *copy_function* argument to be able to provide a custom copy
158 function.
Georg Brandl116aa622007-08-15 14:28:22 +0000159
Ezio Melotticb999a32010-04-20 11:26:51 +0000160 .. versionchanged:: 3.2
Tarek Ziadéfb437512010-04-20 08:57:33 +0000161 Added the *ignore_dangling_symlinks* argument to silent dangling symlinks
162 errors when *symlinks* is false.
163
Antoine Pitrou78091e62011-12-29 18:54:15 +0100164 .. versionchanged:: 3.3
165 Copy metadata when *symlinks* is false.
166
Tarek Ziadéfb437512010-04-20 08:57:33 +0000167
Georg Brandl18244152009-09-02 20:34:52 +0000168.. function:: rmtree(path, ignore_errors=False, onerror=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000169
170 .. index:: single: directory; deleting
171
Christian Heimes9bd667a2008-01-20 15:14:11 +0000172 Delete an entire directory tree; *path* must point to a directory (but not a
173 symbolic link to a directory). If *ignore_errors* is true, errors resulting
174 from failed removals will be ignored; if false or omitted, such errors are
175 handled by calling a handler specified by *onerror* or, if that is omitted,
176 they raise an exception.
Georg Brandl116aa622007-08-15 14:28:22 +0000177
Christian Heimes9bd667a2008-01-20 15:14:11 +0000178 If *onerror* is provided, it must be a callable that accepts three
179 parameters: *function*, *path*, and *excinfo*. The first parameter,
180 *function*, is the function which raised the exception; it will be
181 :func:`os.path.islink`, :func:`os.listdir`, :func:`os.remove` or
182 :func:`os.rmdir`. The second parameter, *path*, will be the path name passed
183 to *function*. The third parameter, *excinfo*, will be the exception
184 information return by :func:`sys.exc_info`. Exceptions raised by *onerror*
185 will not be caught.
186
Georg Brandl116aa622007-08-15 14:28:22 +0000187
188.. function:: move(src, dst)
189
Éric Araujo14382dc2011-07-28 22:49:11 +0200190 Recursively move a file or directory (*src*) to another location (*dst*).
Georg Brandl116aa622007-08-15 14:28:22 +0000191
Éric Araujo14382dc2011-07-28 22:49:11 +0200192 If the destination is a directory or a symlink to a directory, then *src* is
193 moved inside that directory.
194
195 The destination directory must not already exist. If the destination already
196 exists but is not a directory, it may be overwritten depending on
197 :func:`os.rename` semantics.
198
199 If the destination is on the current filesystem, then :func:`os.rename` is
200 used. Otherwise, *src* is copied (using :func:`copy2`) to *dst* and then
Antoine Pitrou0a08d7a2012-01-06 20:16:19 +0100201 removed. In case of symlinks, a new symlink pointing to the target of *src*
202 will be created in or as *dst* and *src* will be removed.
203
204 .. versionchanged:: 3.3
205 Added explicit symlink handling for foreign filesystems, thus adapting
206 it to the behavior of GNU's :program:`mv`.
Georg Brandl116aa622007-08-15 14:28:22 +0000207
Giampaolo Rodola'210e7ca2011-07-01 13:55:36 +0200208.. function:: disk_usage(path)
209
Éric Araujoe4d5b8e2011-08-08 16:51:11 +0200210 Return disk usage statistics about the given path as a :term:`named tuple`
211 with the attributes *total*, *used* and *free*, which are the amount of
212 total, used and free space, in bytes.
Giampaolo Rodola'210e7ca2011-07-01 13:55:36 +0200213
214 .. versionadded:: 3.3
215
216 Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000217
Sandro Tosid902a142011-08-22 23:28:27 +0200218.. function:: chown(path, user=None, group=None)
219
220 Change owner *user* and/or *group* of the given *path*.
221
222 *user* can be a system user name or a uid; the same applies to *group*. At
223 least one argument is required.
224
225 See also :func:`os.chown`, the underlying function.
226
227 Availability: Unix.
228
229 .. versionadded:: 3.3
230
231
Georg Brandl116aa622007-08-15 14:28:22 +0000232.. exception:: Error
233
Éric Araujo14382dc2011-07-28 22:49:11 +0200234 This exception collects exceptions that are raised during a multi-file
235 operation. For :func:`copytree`, the exception argument is a list of 3-tuples
236 (*srcname*, *dstname*, *exception*).
Georg Brandl116aa622007-08-15 14:28:22 +0000237
Georg Brandl116aa622007-08-15 14:28:22 +0000238
Éric Araujof2fbb9c2012-01-16 16:55:55 +0100239.. _shutil-copytree-example:
Georg Brandl116aa622007-08-15 14:28:22 +0000240
Tarek Ziadé396fad72010-02-23 05:30:31 +0000241copytree example
242::::::::::::::::
Georg Brandl116aa622007-08-15 14:28:22 +0000243
244This example is the implementation of the :func:`copytree` function, described
245above, with the docstring omitted. It demonstrates many of the other functions
246provided by this module. ::
247
248 def copytree(src, dst, symlinks=False):
249 names = os.listdir(src)
250 os.makedirs(dst)
251 errors = []
252 for name in names:
253 srcname = os.path.join(src, name)
254 dstname = os.path.join(dst, name)
255 try:
256 if symlinks and os.path.islink(srcname):
257 linkto = os.readlink(srcname)
258 os.symlink(linkto, dstname)
259 elif os.path.isdir(srcname):
260 copytree(srcname, dstname, symlinks)
261 else:
262 copy2(srcname, dstname)
263 # XXX What about devices, sockets etc.?
264 except (IOError, os.error) as why:
265 errors.append((srcname, dstname, str(why)))
266 # catch the Error from the recursive copytree so that we can
267 # continue with other files
268 except Error as err:
269 errors.extend(err.args[0])
270 try:
271 copystat(src, dst)
272 except WindowsError:
273 # can't copy file access times on Windows
274 pass
275 except OSError as why:
276 errors.extend((src, dst, str(why)))
277 if errors:
Collin Winterc79461b2007-09-01 23:34:30 +0000278 raise Error(errors)
Georg Brandl116aa622007-08-15 14:28:22 +0000279
Tarek Ziadé396fad72010-02-23 05:30:31 +0000280Another example that uses the :func:`ignore_patterns` helper::
281
282 from shutil import copytree, ignore_patterns
283
284 copytree(source, destination, ignore=ignore_patterns('*.pyc', 'tmp*'))
285
286This will copy everything except ``.pyc`` files and files or directories whose
287name starts with ``tmp``.
288
289Another example that uses the *ignore* argument to add a logging call::
290
291 from shutil import copytree
292 import logging
293
294 def _logpath(path, names):
295 logging.info('Working in %s' % path)
296 return [] # nothing will be ignored
297
298 copytree(source, destination, ignore=_logpath)
299
300
Raymond Hettinger0929b1f2011-01-23 11:29:08 +0000301.. _archiving-operations:
302
303Archiving operations
304--------------------
Tarek Ziadé396fad72010-02-23 05:30:31 +0000305
Éric Araujof2fbb9c2012-01-16 16:55:55 +0100306High-level utilities to create and read compressed and archived files are also
307provided. They rely on the :mod:`zipfile` and :mod:`tarfile` modules.
308
Tarek Ziadé396fad72010-02-23 05:30:31 +0000309.. function:: make_archive(base_name, format, [root_dir, [base_dir, [verbose, [dry_run, [owner, [group, [logger]]]]]]])
310
Raymond Hettinger0929b1f2011-01-23 11:29:08 +0000311 Create an archive file (such as zip or tar) and return its name.
Tarek Ziadé396fad72010-02-23 05:30:31 +0000312
313 *base_name* is the name of the file to create, including the path, minus
314 any format-specific extension. *format* is the archive format: one of
Tarek Ziadéffa155a2010-04-29 13:34:35 +0000315 "zip", "tar", "bztar" (if the :mod:`bz2` module is available) or "gztar".
Tarek Ziadé396fad72010-02-23 05:30:31 +0000316
317 *root_dir* is a directory that will be the root directory of the
Raymond Hettinger0929b1f2011-01-23 11:29:08 +0000318 archive; for example, we typically chdir into *root_dir* before creating the
Tarek Ziadé396fad72010-02-23 05:30:31 +0000319 archive.
320
321 *base_dir* is the directory where we start archiving from;
Ezio Melotticb999a32010-04-20 11:26:51 +0000322 i.e. *base_dir* will be the common prefix of all files and
Tarek Ziadé396fad72010-02-23 05:30:31 +0000323 directories in the archive.
324
325 *root_dir* and *base_dir* both default to the current directory.
326
327 *owner* and *group* are used when creating a tar archive. By default,
328 uses the current owner and group.
329
Éric Araujo06c42a32011-11-07 17:31:07 +0100330 *logger* must be an object compatible with :pep:`282`, usually an instance of
331 :class:`logging.Logger`.
Raymond Hettinger0929b1f2011-01-23 11:29:08 +0000332
Ezio Melottif8754a62010-03-21 07:16:43 +0000333 .. versionadded:: 3.2
Tarek Ziadé396fad72010-02-23 05:30:31 +0000334
335
336.. function:: get_archive_formats()
337
Éric Araujo14382dc2011-07-28 22:49:11 +0200338 Return a list of supported formats for archiving.
Tarek Ziadé396fad72010-02-23 05:30:31 +0000339 Each element of the returned sequence is a tuple ``(name, description)``
340
341 By default :mod:`shutil` provides these formats:
342
343 - *gztar*: gzip'ed tar-file
Tarek Ziadéffa155a2010-04-29 13:34:35 +0000344 - *bztar*: bzip2'ed tar-file (if the :mod:`bz2` module is available.)
Tarek Ziadé396fad72010-02-23 05:30:31 +0000345 - *tar*: uncompressed tar file
346 - *zip*: ZIP file
347
348 You can register new formats or provide your own archiver for any existing
349 formats, by using :func:`register_archive_format`.
350
Ezio Melottif8754a62010-03-21 07:16:43 +0000351 .. versionadded:: 3.2
Tarek Ziadé396fad72010-02-23 05:30:31 +0000352
353
354.. function:: register_archive_format(name, function, [extra_args, [description]])
355
Éric Araujo14382dc2011-07-28 22:49:11 +0200356 Register an archiver for the format *name*. *function* is a callable that
Tarek Ziadé396fad72010-02-23 05:30:31 +0000357 will be used to invoke the archiver.
358
Raymond Hettinger0929b1f2011-01-23 11:29:08 +0000359 If given, *extra_args* is a sequence of ``(name, value)`` pairs that will be
Tarek Ziadé396fad72010-02-23 05:30:31 +0000360 used as extra keywords arguments when the archiver callable is used.
361
362 *description* is used by :func:`get_archive_formats` which returns the
363 list of archivers. Defaults to an empty list.
364
Ezio Melottif8754a62010-03-21 07:16:43 +0000365 .. versionadded:: 3.2
Tarek Ziadé396fad72010-02-23 05:30:31 +0000366
367
Tarek Ziadé6ac91722010-04-28 17:51:36 +0000368.. function:: unregister_archive_format(name)
Tarek Ziadé396fad72010-02-23 05:30:31 +0000369
370 Remove the archive format *name* from the list of supported formats.
371
Ezio Melottif8754a62010-03-21 07:16:43 +0000372 .. versionadded:: 3.2
Tarek Ziadé396fad72010-02-23 05:30:31 +0000373
374
Tarek Ziadé6ac91722010-04-28 17:51:36 +0000375.. function:: unpack_archive(filename[, extract_dir[, format]])
376
377 Unpack an archive. *filename* is the full path of the archive.
378
379 *extract_dir* is the name of the target directory where the archive is
380 unpacked. If not provided, the current working directory is used.
381
382 *format* is the archive format: one of "zip", "tar", or "gztar". Or any
383 other format registered with :func:`register_unpack_format`. If not
384 provided, :func:`unpack_archive` will use the archive file name extension
385 and see if an unpacker was registered for that extension. In case none is
386 found, a :exc:`ValueError` is raised.
387
388 .. versionadded:: 3.2
389
390
Raymond Hettinger0929b1f2011-01-23 11:29:08 +0000391.. function:: register_unpack_format(name, extensions, function[, extra_args[, description]])
Tarek Ziadé6ac91722010-04-28 17:51:36 +0000392
393 Registers an unpack format. *name* is the name of the format and
394 *extensions* is a list of extensions corresponding to the format, like
395 ``.zip`` for Zip files.
396
397 *function* is the callable that will be used to unpack archives. The
398 callable will receive the path of the archive, followed by the directory
399 the archive must be extracted to.
400
401 When provided, *extra_args* is a sequence of ``(name, value)`` tuples that
402 will be passed as keywords arguments to the callable.
403
404 *description* can be provided to describe the format, and will be returned
405 by the :func:`get_unpack_formats` function.
406
407 .. versionadded:: 3.2
408
409
410.. function:: unregister_unpack_format(name)
411
412 Unregister an unpack format. *name* is the name of the format.
413
414 .. versionadded:: 3.2
415
416
417.. function:: get_unpack_formats()
418
419 Return a list of all registered formats for unpacking.
420 Each element of the returned sequence is a tuple
421 ``(name, extensions, description)``.
422
423 By default :mod:`shutil` provides these formats:
424
425 - *gztar*: gzip'ed tar-file
Tarek Ziadéffa155a2010-04-29 13:34:35 +0000426 - *bztar*: bzip2'ed tar-file (if the :mod:`bz2` module is available.)
Tarek Ziadé6ac91722010-04-28 17:51:36 +0000427 - *tar*: uncompressed tar file
428 - *zip*: ZIP file
429
430 You can register new formats or provide your own unpacker for any existing
431 formats, by using :func:`register_unpack_format`.
432
433 .. versionadded:: 3.2
434
435
Éric Araujof2fbb9c2012-01-16 16:55:55 +0100436.. _shutil-archiving-example:
Tarek Ziadé6ac91722010-04-28 17:51:36 +0000437
Tarek Ziadé396fad72010-02-23 05:30:31 +0000438Archiving example
439:::::::::::::::::
440
441In this example, we create a gzip'ed tar-file archive containing all files
442found in the :file:`.ssh` directory of the user::
443
444 >>> from shutil import make_archive
445 >>> import os
446 >>> archive_name = os.path.expanduser(os.path.join('~', 'myarchive'))
447 >>> root_dir = os.path.expanduser(os.path.join('~', '.ssh'))
448 >>> make_archive(archive_name, 'gztar', root_dir)
449 '/Users/tarek/myarchive.tar.gz'
450
451The resulting archive contains::
452
453 $ tar -tzvf /Users/tarek/myarchive.tar.gz
454 drwx------ tarek/staff 0 2010-02-01 16:23:40 ./
455 -rw-r--r-- tarek/staff 609 2008-06-09 13:26:54 ./authorized_keys
456 -rwxr-xr-x tarek/staff 65 2008-06-09 13:26:54 ./config
457 -rwx------ tarek/staff 668 2008-06-09 13:26:54 ./id_dsa
458 -rwxr-xr-x tarek/staff 609 2008-06-09 13:26:54 ./id_dsa.pub
459 -rw------- tarek/staff 1675 2008-06-09 13:26:54 ./id_rsa
460 -rw-r--r-- tarek/staff 397 2008-06-09 13:26:54 ./id_rsa.pub
461 -rw-r--r-- tarek/staff 37192 2010-02-06 18:23:10 ./known_hosts
Antoine Pitroubcf2b592012-02-08 23:28:36 +0100462
463
464Querying the size of the output terminal
465----------------------------------------
466
467.. versionadded:: 3.3
468
469.. function:: get_terminal_size(fallback=(columns, lines))
470
471 Get the size of the terminal window.
472
473 For each of the two dimensions, the environment variable, ``COLUMNS``
474 and ``LINES`` respectively, is checked. If the variable is defined and
475 the value is a positive integer, it is used.
476
477 When ``COLUMNS`` or ``LINES`` is not defined, which is the common case,
478 the terminal connected to :data:`sys.__stdout__` is queried
479 by invoking :func:`os.get_terminal_size`.
480
481 If the terminal size cannot be successfully queried, either because
482 the system doesn't support querying, or because we are not
483 connected to a terminal, the value given in ``fallback`` parameter
484 is used. ``fallback`` defaults to ``(80, 24)`` which is the default
485 size used by many terminal emulators.
486
487 The value returned is a named tuple of type :class:`os.terminal_size`.
488
489 See also: The Single UNIX Specification, Version 2,
490 `Other Environment Variables`_.
491
492.. _`Other Environment Variables`:
493 http://pubs.opengroup.org/onlinepubs/7908799/xbd/envvar.html#tag_002_003
494