Debian Codegraph @

Doc/library/shutil.rst

raw
1 :mod:`!shutil` --- High-level file operations
2 =============================================
3
4 .. module:: shutil
5 :synopsis: High-level file operations, including copying.
6
7 .. sectionauthor:: Fred L. Drake, Jr. <[email protected]>
8 .. partly based on the docstrings
9
10 **Source code:** :source:`Lib/shutil.py`
11
12 .. index::
13 single: file; copying
14 single: copying files
15
16 --------------
17
18 The :mod:`shutil` module offers a number of high-level operations on files and
19 collections of files. In particular, functions are provided which support file
20 copying and removal. For operations on individual files, see also the
21 :mod:`os` module.
22
23 .. warning::
24
25 Even the higher-level file copying functions (:func:`shutil.copy`,
26 :func:`shutil.copy2`) cannot copy all file metadata.
27
28 On POSIX platforms, this means that file owner and group are lost as well
29 as ACLs. On Mac OS, the resource fork and other metadata are not used.
30 This means that resources will be lost and file type and creator codes will
31 not be correct. On Windows, file owners, ACLs and alternate data streams
32 are not copied.
33
34
35 .. _file-operations:
36
37 Directory and files operations
38 ------------------------------
39
40 .. function:: copyfileobj(fsrc, fdst[, length])
41
42 Copy the contents of the :term:`file-like object <file object>` *fsrc* to the file-like object *fdst*.
43 The integer *length*, if given, is the buffer size. In particular, a negative
44 *length* value means to copy the data without looping over the source data in
45 chunks; by default the data is read in chunks to avoid uncontrolled memory
46 consumption. Note that if the current file position of the *fsrc* object is not
47 0, only the contents from the current file position to the end of the file will
48 be copied.
49
50
51 .. function:: copyfile(src, dst, *, follow_symlinks=True)
52
53 Copy the contents (no metadata) of the file named *src* to a file named
54 *dst* and return *dst* in the most efficient way possible.
55 *src* and *dst* are :term:`path-like objects <path-like object>` or path names given as strings.
56
57 *dst* must be the complete target file name; look at :func:`~shutil.copy`
58 for a copy that accepts a target directory path. If *src* and *dst*
59 specify the same file, :exc:`SameFileError` is raised.
60
61 The destination location must be writable; otherwise, an :exc:`OSError`
62 exception will be raised. If *dst* already exists, it will be replaced.
63 Special files such as character or block devices and pipes cannot be
64 copied with this function.
65
66 If *follow_symlinks* is false and *src* is a symbolic link,
67 a new symbolic link will be created instead of copying the
68 file *src* points to.
69
70 .. audit-event:: shutil.copyfile src,dst shutil.copyfile
71
72 .. versionchanged:: 3.3
73 :exc:`IOError` used to be raised instead of :exc:`OSError`.
74 Added *follow_symlinks* argument.
75 Now returns *dst*.
76
77 .. versionchanged:: 3.4
78 Raise :exc:`SameFileError` instead of :exc:`Error`. Since the former is
79 a subclass of the latter, this change is backward compatible.
80
81 .. versionchanged:: 3.8
82 Platform-specific fast-copy syscalls may be used internally in order to
83 copy the file more efficiently. See
84 :ref:`shutil-platform-dependent-efficient-copy-operations` section.
85
86 .. exception:: SpecialFileError
87
88 This exception is raised when :func:`copyfile` or :func:`copytree` attempt
89 to copy a named pipe.
90
91 .. versionadded:: 2.7
92
93 .. exception:: SameFileError
94
95 This exception is raised if source and destination in :func:`copyfile`
96 are the same file.
97
98 .. versionadded:: 3.4
99
100
101 .. function:: copymode(src, dst, *, follow_symlinks=True)
102
103 Copy the permission bits from *src* to *dst*. The file contents, owner, and
104 group are unaffected. *src* and *dst* are :term:`path-like objects <path-like object>` or path names
105 given as strings.
106 If *follow_symlinks* is false, and both *src* and *dst* are symbolic links,
107 :func:`copymode` will attempt to modify the mode of *dst* itself (rather
108 than the file it points to). This functionality is not available on every
109 platform; please see :func:`copystat` for more information. If
110 :func:`copymode` cannot modify symbolic links on the local platform, and it
111 is asked to do so, it will do nothing and return.
112
113 .. audit-event:: shutil.copymode src,dst shutil.copymode
114
115 .. versionchanged:: 3.3
116 Added *follow_symlinks* argument.
117
118 .. function:: copystat(src, dst, *, follow_symlinks=True)
119
120 Copy the permission bits, last access time, last modification time, and
121 flags from *src* to *dst*. On Linux, :func:`copystat` also copies the
122 "extended attributes" where possible. The file contents, owner, and
123 group are unaffected. *src* and *dst* are :term:`path-like objects <path-like object>` or path
124 names given as strings.
125
126 If *follow_symlinks* is false, and *src* and *dst* both
127 refer to symbolic links, :func:`copystat` will operate on
128 the symbolic links themselves rather than the files the
129 symbolic links refer to—reading the information from the
130 *src* symbolic link, and writing the information to the
131 *dst* symbolic link.
132
133 .. note::
134
135 Not all platforms provide the ability to examine and
136 modify symbolic links. Python itself can tell you what
137 functionality is locally available.
138
139 * If ``os.chmod in os.supports_follow_symlinks`` is
140 ``True``, :func:`copystat` can modify the permission
141 bits of a symbolic link.
142
143 * If ``os.utime in os.supports_follow_symlinks`` is
144 ``True``, :func:`copystat` can modify the last access
145 and modification times of a symbolic link.
146
147 * If ``os.chflags in os.supports_follow_symlinks`` is
148 ``True``, :func:`copystat` can modify the flags of
149 a symbolic link. (``os.chflags`` is not available on
150 all platforms.)
151
152 On platforms where some or all of this functionality
153 is unavailable, when asked to modify a symbolic link,
154 :func:`copystat` will copy everything it can.
155 :func:`copystat` never returns failure.
156
157 Please see :data:`os.supports_follow_symlinks`
158 for more information.
159
160 .. audit-event:: shutil.copystat src,dst shutil.copystat
161
162 .. versionchanged:: 3.3
163 Added *follow_symlinks* argument and support for Linux extended attributes.
164
165 .. function:: copy(src, dst, *, follow_symlinks=True)
166
167 Copies the file *src* to the file or directory *dst*. *src* and *dst*
168 should be :term:`path-like objects <path-like object>` or strings. If
169 *dst* specifies a directory, the file will be copied into *dst* using the
170 base filename from *src*. If *dst* specifies a file that already exists,
171 it will be replaced. Returns the path to the newly created file.
172
173 If *follow_symlinks* is false, and *src* is a symbolic link,
174 *dst* will be created as a symbolic link. If *follow_symlinks*
175 is true and *src* is a symbolic link, *dst* will be a copy of
176 the file *src* refers to.
177
178 :func:`~shutil.copy` copies the file data and the file's permission
179 mode (see :func:`os.chmod`). Other metadata, like the
180 file's creation and modification times, is not preserved.
181 To preserve all file metadata from the original, use
182 :func:`~shutil.copy2` instead.
183
184 .. audit-event:: shutil.copyfile src,dst shutil.copy
185
186 .. audit-event:: shutil.copymode src,dst shutil.copy
187
188 .. versionchanged:: 3.3
189 Added *follow_symlinks* argument.
190 Now returns path to the newly created file.
191
192 .. versionchanged:: 3.8
193 Platform-specific fast-copy syscalls may be used internally in order to
194 copy the file more efficiently. See
195 :ref:`shutil-platform-dependent-efficient-copy-operations` section.
196
197 .. function:: copy2(src, dst, *, follow_symlinks=True)
198
199 Identical to :func:`~shutil.copy` except that :func:`copy2`
200 also attempts to preserve file metadata.
201
202 When *follow_symlinks* is false, and *src* is a symbolic
203 link, :func:`copy2` attempts to copy all metadata from the
204 *src* symbolic link to the newly created *dst* symbolic link.
205 However, this functionality is not available on all platforms.
206 On platforms where some or all of this functionality is
207 unavailable, :func:`copy2` will preserve all the metadata
208 it can; :func:`copy2` never raises an exception because it
209 cannot preserve file metadata.
210
211 :func:`copy2` uses :func:`copystat` to copy the file metadata.
212 Please see :func:`copystat` for more information
213 about platform support for modifying symbolic link metadata.
214
215 .. audit-event:: shutil.copyfile src,dst shutil.copy2
216
217 .. audit-event:: shutil.copystat src,dst shutil.copy2
218
219 .. versionchanged:: 3.3
220 Added *follow_symlinks* argument, try to copy extended
221 file system attributes too (currently Linux only).
222 Now returns path to the newly created file.
223
224 .. versionchanged:: 3.8
225 Platform-specific fast-copy syscalls may be used internally in order to
226 copy the file more efficiently. See
227 :ref:`shutil-platform-dependent-efficient-copy-operations` section.
228
229 .. function:: ignore_patterns(*patterns)
230
231 This factory function creates a function that can be used as a callable for
232 :func:`copytree`\'s *ignore* argument, ignoring files and directories that
233 match one of the glob-style *patterns* provided. See the example below.
234
235
236 .. function:: copytree(src, dst, symlinks=False, ignore=None, \
237 copy_function=copy2, ignore_dangling_symlinks=False, \
238 dirs_exist_ok=False)
239
240 Recursively copy an entire directory tree rooted at *src* to a directory
241 named *dst* and return the destination directory. All intermediate
242 directories needed to contain *dst* will also be created by default.
243
244 Permissions and times of directories are copied with :func:`copystat`,
245 individual files are copied using :func:`~shutil.copy2`.
246
247 If *symlinks* is true, symbolic links in the source tree are represented as
248 symbolic links in the new tree and the metadata of the original links will
249 be copied as far as the platform allows; if false or omitted, the contents
250 and metadata of the linked files are copied to the new tree.
251
252 When *symlinks* is false, if the file pointed to by the symlink doesn't
253 exist, an exception will be added in the list of errors raised in
254 an :exc:`Error` exception at the end of the copy process.
255 You can set the optional *ignore_dangling_symlinks* flag to true if you
256 want to silence this exception. Notice that this option has no effect
257 on platforms that don't support :func:`os.symlink`.
258
259 If *ignore* is given, it must be a callable that will receive as its
260 arguments the directory being visited by :func:`copytree`, and a list of its
261 contents, as returned by :func:`os.listdir`. Since :func:`copytree` is
262 called recursively, the *ignore* callable will be called once for each
263 directory that is copied. The callable must return a sequence of directory
264 and file names relative to the current directory (i.e. a subset of the items
265 in its second argument); these names will then be ignored in the copy
266 process. :func:`ignore_patterns` can be used to create such a callable that
267 ignores names based on glob-style patterns.
268
269 If exception(s) occur, an :exc:`Error` is raised with a list of reasons.
270
271 If *copy_function* is given, it must be a callable that will be used to copy
272 each file. It will be called with the source path and the destination path
273 as arguments. By default, :func:`~shutil.copy2` is used, but any function
274 that supports the same signature (like :func:`~shutil.copy`) can be used.
275
276 If *dirs_exist_ok* is false (the default) and *dst* already exists, a
277 :exc:`FileExistsError` is raised. If *dirs_exist_ok* is true, the copying
278 operation will continue if it encounters existing directories, and files
279 within the *dst* tree will be overwritten by corresponding files from the
280 *src* tree.
281
282 .. audit-event:: shutil.copytree src,dst shutil.copytree
283
284 .. versionchanged:: 3.2
285 Added the *copy_function* argument to be able to provide a custom copy
286 function.
287 Added the *ignore_dangling_symlinks* argument to silence dangling symlinks
288 errors when *symlinks* is false.
289
290 .. versionchanged:: 3.3
291 Copy metadata when *symlinks* is false.
292 Now returns *dst*.
293
294 .. versionchanged:: 3.8
295 Platform-specific fast-copy syscalls may be used internally in order to
296 copy the file more efficiently. See
297 :ref:`shutil-platform-dependent-efficient-copy-operations` section.
298
299 .. versionchanged:: 3.8
300 Added the *dirs_exist_ok* parameter.
301
302 .. function:: rmtree(path, ignore_errors=False, onerror=None, *, onexc=None, dir_fd=None)
303
304 .. index:: single: directory; deleting
305
306 Delete an entire directory tree; *path* must point to a directory (but not a
307 symbolic link to a directory). If *ignore_errors* is true, errors resulting
308 from failed removals will be ignored; if false or omitted, such errors are
309 handled by calling a handler specified by *onexc* or *onerror* or, if both
310 are omitted, exceptions are propagated to the caller.
311
312 This function can support :ref:`paths relative to directory descriptors
313 <dir_fd>`.
314
315 .. note::
316
317 On platforms that support the necessary fd-based functions a symlink
318 attack resistant version of :func:`rmtree` is used by default. On other
319 platforms, the :func:`rmtree` implementation is susceptible to a symlink
320 attack: given proper timing and circumstances, attackers can manipulate
321 symlinks on the filesystem to delete files they wouldn't be able to access
322 otherwise. Applications can use the :data:`rmtree.avoids_symlink_attacks`
323 function attribute to determine which case applies.
324
325 If *onexc* is provided, it must be a callable that accepts three parameters:
326 *function*, *path*, and *excinfo*.
327
328 The first parameter, *function*, is the function which raised the exception;
329 it depends on the platform and implementation. The second parameter,
330 *path*, will be the path name passed to *function*. The third parameter,
331 *excinfo*, is the exception that was raised. Exceptions raised by *onexc*
332 will not be caught.
333
334 The deprecated *onerror* is similar to *onexc*, except that the third
335 parameter it receives is the tuple returned from :func:`sys.exc_info`.
336
337 .. seealso::
338 :ref:`shutil-rmtree-example` for an example of handling the removal
339 of a directory tree that contains read-only files.
340
341 .. audit-event:: shutil.rmtree path,dir_fd shutil.rmtree
342
343 .. versionchanged:: 3.3
344 Added a symlink attack resistant version that is used automatically
345 if platform supports fd-based functions.
346
347 .. versionchanged:: 3.8
348 On Windows, will no longer delete the contents of a directory junction
349 before removing the junction.
350
351 .. versionchanged:: 3.11
352 Added the *dir_fd* parameter.
353
354 .. versionchanged:: 3.12
355 Added the *onexc* parameter, deprecated *onerror*.
356
357 .. versionchanged:: 3.13
358 :func:`!rmtree` now ignores :exc:`FileNotFoundError` exceptions for all
359 but the top-level path.
360 Exceptions other than :exc:`OSError` and subclasses of :exc:`!OSError`
361 are now always propagated to the caller.
362
363 .. attribute:: rmtree.avoids_symlink_attacks
364
365 Indicates whether the current platform and implementation provides a
366 symlink attack resistant version of :func:`rmtree`. Currently this is
367 only true for platforms supporting fd-based directory access functions.
368
369 .. versionadded:: 3.3
370
371
372 .. function:: move(src, dst, copy_function=copy2)
373
374 Recursively move a file or directory (*src*) to another location and return
375 the destination.
376
377 If *dst* is an existing directory or a symlink to a directory, then *src*
378 is moved inside that directory. The destination path in that directory must
379 not already exist.
380
381 If *dst* already exists but is not a directory, it may be overwritten
382 depending on :func:`os.rename` semantics.
383
384 If the destination is on the current filesystem, then :func:`os.rename` is
385 used. Otherwise, *src* is copied to the destination using *copy_function*
386 and then removed. In case of symlinks, a new symlink pointing to the target
387 of *src* will be created as the destination and *src* will be removed.
388
389 If *copy_function* is given, it must be a callable that takes two arguments,
390 *src* and the destination, and will be used to copy *src* to the destination
391 if :func:`os.rename` cannot be used. If the source is a directory,
392 :func:`copytree` is called, passing it the *copy_function*. The
393 default *copy_function* is :func:`copy2`. Using :func:`~shutil.copy` as the
394 *copy_function* allows the move to succeed when it is not possible to also
395 copy the metadata, at the expense of not copying any of the metadata.
396
397 .. audit-event:: shutil.move src,dst shutil.move
398
399 .. versionchanged:: 3.3
400 Added explicit symlink handling for foreign filesystems, thus adapting
401 it to the behavior of GNU's :program:`mv`.
402 Now returns *dst*.
403
404 .. versionchanged:: 3.5
405 Added the *copy_function* keyword argument.
406
407 .. versionchanged:: 3.8
408 Platform-specific fast-copy syscalls may be used internally in order to
409 copy the file more efficiently. See
410 :ref:`shutil-platform-dependent-efficient-copy-operations` section.
411
412 .. versionchanged:: 3.9
413 Accepts a :term:`path-like object` for both *src* and *dst*.
414
415 .. function:: disk_usage(path)
416
417 Return disk usage statistics about the given path as a :term:`named tuple`
418 with the attributes *total*, *used* and *free*, which are the amount of
419 total, used and free space, in bytes. *path* may be a file or a
420 directory.
421
422 .. note::
423
424 On Unix filesystems, *path* must point to a path within a **mounted**
425 filesystem partition. On those platforms, CPython doesn't attempt to
426 retrieve disk usage information from non-mounted filesystems.
427
428 .. versionadded:: 3.3
429
430 .. versionchanged:: 3.8
431 On Windows, *path* can now be a file or directory.
432
433 .. availability:: Unix, Windows.
434
435 .. function:: chown(path, user=None, group=None, *, dir_fd=None, \
436 follow_symlinks=True)
437
438 Change owner *user* and/or *group* of the given *path*.
439
440 *user* can be a system user name or a uid; the same applies to *group*. At
441 least one argument is required.
442
443 See also :func:`os.chown`, the underlying function.
444
445 .. audit-event:: shutil.chown path,user,group shutil.chown
446
447 .. availability:: Unix.
448
449 .. versionadded:: 3.3
450
451 .. versionchanged:: 3.13
452 Added *dir_fd* and *follow_symlinks* parameters.
453
454
455 .. function:: which(cmd, mode=os.F_OK | os.X_OK, path=None)
456
457 Return the path to an executable which would be run if the given *cmd* was
458 called. If no *cmd* would be called, return ``None``.
459
460 *mode* is a permission mask passed to :func:`os.access`, by default
461 determining if the file exists and is executable.
462
463 *path* is a "``PATH`` string" specifying the directories to look in,
464 delimited by :data:`os.pathsep`. When no *path* is specified, the
465 :envvar:`PATH` environment variable is read from :data:`os.environ`,
466 falling back to :data:`os.defpath` if it is not set.
467
468 If *cmd* contains a directory component, :func:`!which` only checks the
469 specified path directly and does not search the directories listed in
470 *path* or in the system's :envvar:`PATH` environment variable.
471
472 On Windows, the current directory is prepended to the *path* if *mode* does
473 not include ``os.X_OK``. When the *mode* does include ``os.X_OK``, the
474 Windows API ``NeedCurrentDirectoryForExePathW`` will be consulted to
475 determine if the current directory should be prepended to *path*. To avoid
476 consulting the current working directory for executables: set the environment
477 variable ``NoDefaultCurrentDirectoryInExePath``.
478
479 Also on Windows, the :envvar:`PATHEXT` environment variable is used to
480 resolve commands that may not already include an extension. For example,
481 if you call ``shutil.which("python")``, :func:`which` will search ``PATHEXT``
482 to know that it should look for ``python.exe`` within the *path*
483 directories. For example, on Windows::
484
485 >>> shutil.which("python")
486 'C:\\Python33\\python.EXE'
487
488 This is also applied when *cmd* is a path that contains a directory
489 component::
490
491 >>> shutil.which("C:\\Python33\\python")
492 'C:\\Python33\\python.EXE'
493
494 .. versionadded:: 3.3
495
496 .. versionchanged:: 3.8
497 The :class:`bytes` type is now accepted. If *cmd* type is
498 :class:`bytes`, the result type is also :class:`bytes`.
499
500 .. versionchanged:: 3.12
501 On Windows, the current directory is no longer prepended to the search
502 path if *mode* includes ``os.X_OK`` and WinAPI
503 ``NeedCurrentDirectoryForExePathW(cmd)`` is false, else the current
504 directory is prepended even if it is already in the search path;
505 ``PATHEXT`` is used now even when *cmd* includes a directory component
506 or ends with an extension that is in ``PATHEXT``; and filenames that
507 have no extension can now be found.
508
509 .. exception:: Error
510
511 This exception collects exceptions that are raised during a multi-file
512 operation. For :func:`copytree`, the exception argument is a list of 3-tuples
513 (*srcname*, *dstname*, *exception*).
514
515 .. _shutil-platform-dependent-efficient-copy-operations:
516
517 Platform-dependent efficient copy operations
518 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
519
520 Starting from Python 3.8, all functions involving a file copy
521 (:func:`copyfile`, :func:`~shutil.copy`, :func:`copy2`,
522 :func:`copytree`, and :func:`move`) may use
523 platform-specific "fast-copy" syscalls in order to copy the file more
524 efficiently (see :issue:`33671`).
525 "fast-copy" means that the copying operation occurs within the kernel, avoiding
526 the use of userspace buffers in Python as in "``outfd.write(infd.read())``".
527
528 On macOS `fcopyfile`_ is used to copy the file content (not metadata).
529
530 On Linux :func:`os.sendfile` is used.
531
532 On Windows :func:`shutil.copyfile` uses a bigger default buffer size (1 MiB
533 instead of 64 KiB) and a :func:`memoryview`-based variant of
534 :func:`shutil.copyfileobj` is used.
535
536 If the fast-copy operation fails and no data was written in the destination
537 file then shutil will silently fallback on using less efficient
538 :func:`copyfileobj` function internally.
539
540 .. versionchanged:: 3.8
541
542 .. _shutil-copytree-example:
543
544 copytree example
545 ~~~~~~~~~~~~~~~~
546
547 An example that uses the :func:`ignore_patterns` helper::
548
549 from shutil import copytree, ignore_patterns
550
551 copytree(source, destination, ignore=ignore_patterns('*.pyc', 'tmp*'))
552
553 This will copy everything except ``.pyc`` files and files or directories whose
554 name starts with ``tmp``.
555
556 Another example that uses the *ignore* argument to add a logging call::
557
558 from shutil import copytree
559 import logging
560
561 def _logpath(path, names):
562 logging.info('Working in %s', path)
563 return [] # nothing will be ignored
564
565 copytree(source, destination, ignore=_logpath)
566
567
568 .. _shutil-rmtree-example:
569
570 rmtree example
571 ~~~~~~~~~~~~~~
572
573 This example shows how to remove a directory tree on Windows where some
574 of the files have their read-only bit set. It uses the onexc callback
575 to clear the readonly bit and reattempt the remove. Any subsequent failure
576 will propagate. ::
577
578 import os, stat
579 import shutil
580
581 def remove_readonly(func, path, _):
582 "Clear the readonly bit and reattempt the removal"
583 os.chmod(path, stat.S_IWRITE)
584 func(path)
585
586 shutil.rmtree(directory, onexc=remove_readonly)
587
588 .. _archiving-operations:
589
590 Archiving operations
591 --------------------
592
593 .. versionadded:: 3.2
594
595 .. versionchanged:: 3.5
596 Added support for the *xztar* format.
597
598
599 High-level utilities to create and read compressed and archived files are also
600 provided. They rely on the :mod:`zipfile` and :mod:`tarfile` modules.
601
602 .. function:: make_archive(base_name, format, [root_dir, [base_dir, [verbose, [dry_run, [owner, [group, [logger]]]]]]])
603
604 Create an archive file (such as zip or tar) and return its name.
605
606 *base_name* is the name of the file to create, including the path, minus
607 any format-specific extension.
608
609 *format* is the archive format: one of
610 "zip" (if the :mod:`zlib` module is available), "tar", "gztar" (if the
611 :mod:`zlib` module is available), "bztar" (if the :mod:`bz2` module is
612 available), or "xztar" (if the :mod:`lzma` module is available).
613
614 *root_dir* is a directory that will be the root directory of the
615 archive, all paths in the archive will be relative to it; for example,
616 we typically chdir into *root_dir* before creating the archive.
617
618 *base_dir* is the directory where we start archiving from;
619 i.e. *base_dir* will be the common prefix of all files and
620 directories in the archive. *base_dir* must be given relative
621 to *root_dir*. See :ref:`shutil-archiving-example-with-basedir` for how to
622 use *base_dir* and *root_dir* together.
623
624 *root_dir* and *base_dir* both default to the current directory.
625
626 If *dry_run* is true, no archive is created, but the operations that would be
627 executed are logged to *logger*.
628
629 *owner* and *group* are used when creating a tar archive. By default,
630 uses the current owner and group.
631
632 *logger* must be an object compatible with :pep:`282`, usually an instance of
633 :class:`logging.Logger`.
634
635 The *verbose* argument is unused and deprecated.
636
637 .. audit-event:: shutil.make_archive base_name,format,root_dir,base_dir shutil.make_archive
638
639 .. note::
640
641 This function is not thread-safe when custom archivers registered
642 with :func:`register_archive_format` do not support the *root_dir*
643 argument. In this case it
644 temporarily changes the current working directory of the process
645 to *root_dir* to perform archiving.
646
647 .. versionchanged:: 3.8
648 The modern pax (POSIX.1-2001) format is now used instead of
649 the legacy GNU format for archives created with ``format="tar"``.
650
651 .. versionchanged:: 3.10.6
652 This function is now made thread-safe during creation of standard
653 ``.zip`` and tar archives.
654
655 .. function:: get_archive_formats()
656
657 Return a list of supported formats for archiving.
658 Each element of the returned sequence is a tuple ``(name, description)``.
659
660 By default :mod:`shutil` provides these formats:
661
662 - *zip*: ZIP file (if the :mod:`zlib` module is available).
663 - *tar*: Uncompressed tar file. Uses POSIX.1-2001 pax format for new archives.
664 - *gztar*: gzip'ed tar-file (if the :mod:`zlib` module is available).
665 - *bztar*: bzip2'ed tar-file (if the :mod:`bz2` module is available).
666 - *xztar*: xz'ed tar-file (if the :mod:`lzma` module is available).
667
668 You can register new formats or provide your own archiver for any existing
669 formats, by using :func:`register_archive_format`.
670
671
672 .. function:: register_archive_format(name, function, [extra_args, [description]])
673
674 Register an archiver for the format *name*.
675
676 *function* is the callable that will be used to unpack archives. The callable
677 will receive the *base_name* of the file to create, followed by the
678 *base_dir* (which defaults to :data:`os.curdir`) to start archiving from.
679 Further arguments are passed as keyword arguments: *owner*, *group*,
680 *dry_run* and *logger* (as passed in :func:`make_archive`).
681
682 If *function* has the custom attribute ``function.supports_root_dir`` set to ``True``,
683 the *root_dir* argument is passed as a keyword argument.
684 Otherwise the current working directory of the process is temporarily
685 changed to *root_dir* before calling *function*.
686 In this case :func:`make_archive` is not thread-safe.
687
688 If given, *extra_args* is a sequence of ``(name, value)`` pairs that will be
689 used as extra keywords arguments when the archiver callable is used.
690
691 *description* is used by :func:`get_archive_formats` which returns the
692 list of archivers. Defaults to an empty string.
693
694 .. versionchanged:: 3.12
695 Added support for functions supporting the *root_dir* argument.
696
697
698 .. function:: unregister_archive_format(name)
699
700 Remove the archive format *name* from the list of supported formats.
701
702
703 .. function:: unpack_archive(filename[, extract_dir[, format[, filter]]])
704
705 Unpack an archive. *filename* is the full path of the archive.
706
707 *extract_dir* is the name of the target directory where the archive is
708 unpacked. If not provided, the current working directory is used.
709
710 *format* is the archive format: one of "zip", "tar", "gztar", "bztar", or
711 "xztar". Or any other format registered with
712 :func:`register_unpack_format`. If not provided, :func:`unpack_archive`
713 will use the archive file name extension and see if an unpacker was
714 registered for that extension. In case none is found,
715 a :exc:`ValueError` is raised.
716
717 The keyword-only *filter* argument is passed to the underlying unpacking
718 function. For zip files, *filter* is not accepted.
719 For tar files, it is recommended to set it to ``'data'``,
720 unless using features specific to tar and UNIX-like filesystems.
721 (See :ref:`tarfile-extraction-filter` for details.)
722 The ``'data'`` filter will become the default for tar files
723 in Python 3.14.
724
725 .. audit-event:: shutil.unpack_archive filename,extract_dir,format shutil.unpack_archive
726
727 .. warning::
728
729 Never extract archives from untrusted sources without prior inspection.
730 It is possible that files are created outside of the path specified in
731 the *extract_dir* argument, e.g. members that have absolute filenames
732 starting with "/" or filenames with two dots "..".
733
734 .. versionchanged:: 3.7
735 Accepts a :term:`path-like object` for *filename* and *extract_dir*.
736
737 .. versionchanged:: 3.12
738 Added the *filter* argument.
739
740 .. function:: register_unpack_format(name, extensions, function[, extra_args[, description]])
741
742 Registers an unpack format. *name* is the name of the format and
743 *extensions* is a list of extensions corresponding to the format, like
744 ``.zip`` for Zip files.
745
746 *function* is the callable that will be used to unpack archives. The
747 callable will receive:
748
749 - the path of the archive, as a positional argument;
750 - the directory the archive must be extracted to, as a positional argument;
751 - possibly a *filter* keyword argument, if it was given to
752 :func:`unpack_archive`;
753 - additional keyword arguments, specified by *extra_args* as a sequence
754 of ``(name, value)`` tuples.
755
756 *description* can be provided to describe the format, and will be returned
757 by the :func:`get_unpack_formats` function.
758
759
760 .. function:: unregister_unpack_format(name)
761
762 Unregister an unpack format. *name* is the name of the format.
763
764
765 .. function:: get_unpack_formats()
766
767 Return a list of all registered formats for unpacking.
768 Each element of the returned sequence is a tuple
769 ``(name, extensions, description)``.
770
771 By default :mod:`shutil` provides these formats:
772
773 - *zip*: ZIP file (unpacking compressed files works only if the corresponding
774 module is available).
775 - *tar*: uncompressed tar file.
776 - *gztar*: gzip'ed tar-file (if the :mod:`zlib` module is available).
777 - *bztar*: bzip2'ed tar-file (if the :mod:`bz2` module is available).
778 - *xztar*: xz'ed tar-file (if the :mod:`lzma` module is available).
779
780 You can register new formats or provide your own unpacker for any existing
781 formats, by using :func:`register_unpack_format`.
782
783
784 .. _shutil-archiving-example:
785
786 Archiving example
787 ~~~~~~~~~~~~~~~~~
788
789 In this example, we create a gzip'ed tar-file archive containing all files
790 found in the :file:`.ssh` directory of the user::
791
792 >>> from shutil import make_archive
793 >>> import os
794 >>> archive_name = os.path.expanduser(os.path.join('~', 'myarchive'))
795 >>> root_dir = os.path.expanduser(os.path.join('~', '.ssh'))
796 >>> make_archive(archive_name, 'gztar', root_dir)
797 '/Users/tarek/myarchive.tar.gz'
798
799 The resulting archive contains:
800
801 .. code-block:: shell-session
802
803 $ tar -tzvf /Users/tarek/myarchive.tar.gz
804 drwx------ tarek/staff 0 2010-02-01 16:23:40 ./
805 -rw-r--r-- tarek/staff 609 2008-06-09 13:26:54 ./authorized_keys
806 -rwxr-xr-x tarek/staff 65 2008-06-09 13:26:54 ./config
807 -rwx------ tarek/staff 668 2008-06-09 13:26:54 ./id_dsa
808 -rwxr-xr-x tarek/staff 609 2008-06-09 13:26:54 ./id_dsa.pub
809 -rw------- tarek/staff 1675 2008-06-09 13:26:54 ./id_rsa
810 -rw-r--r-- tarek/staff 397 2008-06-09 13:26:54 ./id_rsa.pub
811 -rw-r--r-- tarek/staff 37192 2010-02-06 18:23:10 ./known_hosts
812
813
814 .. _shutil-archiving-example-with-basedir:
815
816 Archiving example with *base_dir*
817 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
818
819 In this example, similar to the `one above <shutil-archiving-example_>`_,
820 we show how to use :func:`make_archive`, but this time with the usage of
821 *base_dir*. We now have the following directory structure:
822
823 .. code-block:: shell-session
824
825 $ tree tmp
826 tmp
827 └── root
828 └── structure
829 ├── content
830 └── please_add.txt
831 └── do_not_add.txt
832
833 In the final archive, :file:`please_add.txt` should be included, but
834 :file:`do_not_add.txt` should not. Therefore we use the following::
835
836 >>> from shutil import make_archive
837 >>> import os
838 >>> archive_name = os.path.expanduser(os.path.join('~', 'myarchive'))
839 >>> make_archive(
840 ... archive_name,
841 ... 'tar',
842 ... root_dir='tmp/root',
843 ... base_dir='structure/content',
844 ... )
845 '/Users/tarek/myarchive.tar'
846
847 Listing the files in the resulting archive gives us:
848
849 .. code-block:: shell-session
850
851 $ python -m tarfile -l /Users/tarek/myarchive.tar
852 structure/content/
853 structure/content/please_add.txt
854
855
856 Querying the size of the output terminal
857 ----------------------------------------
858
859 .. function:: get_terminal_size(fallback=(columns, lines))
860
861 Get the size of the terminal window.
862
863 For each of the two dimensions, the environment variable, ``COLUMNS``
864 and ``LINES`` respectively, is checked. If the variable is defined and
865 the value is a positive integer, it is used.
866
867 When ``COLUMNS`` or ``LINES`` is not defined, which is the common case,
868 the terminal connected to :data:`sys.__stdout__` is queried
869 by invoking :func:`os.get_terminal_size`.
870
871 If the terminal size cannot be successfully queried, either because
872 the system doesn't support querying, or because we are not
873 connected to a terminal, the value given in ``fallback`` parameter
874 is used. ``fallback`` defaults to ``(80, 24)`` which is the default
875 size used by many terminal emulators.
876
877 The value returned is a named tuple of type :class:`os.terminal_size`.
878
879 See also: The Single UNIX Specification, Version 2,
880 `Other Environment Variables`_.
881
882 .. versionadded:: 3.3
883
884 .. versionchanged:: 3.11
885 The ``fallback`` values are also used if :func:`os.get_terminal_size`
886 returns zeroes.
887
888 .. _`fcopyfile`:
889 http://www.manpagez.com/man/3/copyfile/
890
891 .. _`Other Environment Variables`:
892 https://pubs.opengroup.org/onlinepubs/7908799/xbd/envvar.html#tag_002_003