shutil
— High-level file operations高级文件操作¶
Source code: Lib/shutil.py
The shutil
module offers a number of high-level operations on files and collections of files. shutil
模块提供了对文件和文件集合的许多高级操作。In particular, functions are provided which support file copying and removal. 特别是,提供了支持文件复制和删除的函数。For operations on individual files, see also the 有关单个文件的操作,请参阅os
module.os
模块。
Warning
Even the higher-level file copying functions (即使是更高级的文件复制函数(shutil.copy()
, shutil.copy2()
) cannot copy all file metadata.shutil.copy()
、shutil.copy2()
)也无法复制所有文件元数据。
On POSIX platforms, this means that file owner and group are lost as well as ACLs. 在POSIX平台上,这意味着文件所有者和组以及ACL都会丢失。On Mac OS, the resource fork and other metadata are not used. 在Mac OS上,不使用资源叉和其他元数据。This means that resources will be lost and file type and creator codes will not be correct. 这意味着资源将丢失,文件类型和创建者代码将不正确。On Windows, file owners, ACLs and alternate data streams are not copied.在Windows上,不会复制文件所有者、ACL和备用数据流。
Directory and files operations目录和文件操作¶
-
shutil.
copyfileobj
(fsrc, fdst[, length])¶ Copy the contents of the file-like object fsrc to the file-like object fdst.将类文件对象fsrc的内容复制到类文件对象fdst。The integer length, if given, is the buffer size.整数length(如果给定)是缓冲区大小。In particular, a negative length value means to copy the data without looping over the source data in chunks; by default the data is read in chunks to avoid uncontrolled memory consumption.具体而言,负length值意味着复制数据而不在数据块中循环源数据;默认情况下,数据被分块读取,以避免不受控制的内存消耗。Note that if the current file position of the fsrc object is not 0, only the contents from the current file position to the end of the file will be copied.请注意,如果fsrc对象的当前文件位置不是0,则仅复制从当前文件位置到文件末尾的内容。
-
shutil.
copyfile
(src, dst, *, follow_symlinks=True)¶ Copy the contents (no metadata) of the file named src to a file named dst and return dst in the most efficient way possible.将名为src的文件的内容(无元数据)复制到名为dst的文件中,并以最有效的方式返回dst。src and dst are path-like objects or path names given as strings.src和dst是类似路径的对象或以字符串形式给出的路径名。dst
must be the complete target file name; look at必须是完整的目标文件名;请参阅copy()
for a copy that accepts a target directory path.copy()
,查找接受目标目录路径的副本。If src and dst specify the same file,如果src和dst指定相同的文件,则会引发SameFileError
is raised.SameFileError
。The destination location must be writable; otherwise, an目标位置必须是可写的;否则,将引发OSError
exception will be raised.OSError
。If dst already exists, it will be replaced.如果dst已经存在,它将被替换。Special files such as character or block devices and pipes cannot be copied with this function.无法使用此功能复制特殊文件,如字符或块设备和管道。If follow_symlinks is false and src is a symbolic link, a new symbolic link will be created instead of copying the file src points to.如果follow_symlinks为false
且src为符号链接,则将创建新的符号链接,而不是将src指向的文件复制到。Raises an auditing event使用参数src、dst引发审核事件shutil.copyfile
with argumentssrc
,dst
.shutil.copyfile
。Changed in version 3.3:版本3.3中更改:引发IOError
used to be raised instead ofOSError
.IOError
而不是引发OSError
。Added follow_symlinks argument.添加了follow_symlinks参数。Now returns dst.现在返回dst。Changed in version 3.4:版本3.4中更改:Raise引发SameFileError
instead ofError
.SameFileError
而不是Error
。Since the former is a subclass of the latter, this change is backward compatible.由于前者是后者的子类,因此此更改是向后兼容的。Changed in version 3.8:版本3.8中更改:Platform-specific fast-copy syscalls may be used internally in order to copy the file more efficiently.可以在内部使用特定于平台的快速复制系统调用,以便更有效地复制文件。See Platform-dependent efficient copy operations section.请参阅平台相关高效复制操作一节。
-
exception
shutil.
SameFileError
¶ This exception is raised if source and destination in如果copyfile()
are the same file.copyfile()
中的源和目标是同一个文件,则会引发此异常。New in version 3.4.版本3.4中新增。
-
shutil.
copymode
(src, dst, *, follow_symlinks=True)¶ Copy the permission bits from src to dst. The file contents, owner, and group are unaffected. src and dst are path-like objects or path names given as strings. If follow_symlinks is false, and both src and dst are symbolic links,
copymode()
will attempt to modify the mode of dst itself (rather than the file it points to). This functionality is not available on every platform; please seecopystat()
for more information. Ifcopymode()
cannot modify symbolic links on the local platform, and it is asked to do so, it will do nothing and return.Raises an auditing event使用参数src、dst引发审核事件shutil.copymode
with argumentssrc
,dst
.shutil.copymode
。Changed in version 3.3:版本3.3中更改:Added follow_symlinks argument.添加了follow_symlinks参数。
-
shutil.
copystat
(src, dst, *, follow_symlinks=True)¶ Copy the permission bits, last access time, last modification time, and flags from src to dst. On Linux,
copystat()
also copies the “extended attributes” where possible.The file contents, owner, and group are unaffected.文件内容、所有者和组不受影响。src and dst are path-like objects or path names given as strings.src和dst是类似路径的对象或以字符串形式给出的路径名。If follow_symlinks is false, and src and dst both refer to symbolic links,
copystat()
will operate on the symbolic links themselves rather than the files the symbolic links refer to—reading the information from the src symbolic link, and writing the information to the dst symbolic link.Note
Not all platforms provide the ability to examine and modify symbolic links.并非所有平台都能检查和修改符号链接。Python itself can tell you what functionality is locally available.Python本身可以告诉您哪些功能在本地可用。If
os.chmod in os.supports_follow_symlinks
isTrue
,copystat()
can modify the permission bits of a symbolic link.If
os.utime in os.supports_follow_symlinks
isTrue
,copystat()
can modify the last access and modification times of a symbolic link.If
os.chflags in os.supports_follow_symlinks
isTrue
,copystat()
can modify the flags of a symbolic link. (os.chflags
is not available on all platforms.)
On platforms where some or all of this functionality is unavailable, when asked to modify a symbolic link,
copystat()
will copy everything it can.copystat()
never returns failure.Please see有关更多信息,请参阅os.supports_follow_symlinks
for more information.os.supports_follow_symlinks
。Raises an auditing event
shutil.copystat
with argumentssrc
,dst
.Changed in version 3.3:版本3.3中更改: Added follow_symlinks argument and support for Linux extended attributes.
-
shutil.
copy
(src, dst, *, follow_symlinks=True)¶ Copies the file src to the file or directory dst. src and dst should be path-like objects or strings. If dst specifies a directory, the file will be copied into dst using the base filename from src. Returns the path to the newly created file.
If follow_symlinks is false, and src is a symbolic link, dst will be created as a symbolic link. If follow_symlinks is true and src is a symbolic link, dst will be a copy of the file src refers to.
copy()
copies the file data and the file’s permission mode (seeos.chmod()
). Other metadata, like the file’s creation and modification times, is not preserved. To preserve all file metadata from the original, usecopy2()
instead.Raises an auditing event
shutil.copyfile
with argumentssrc
,dst
.Raises an auditing event
shutil.copymode
with argumentssrc
,dst
.Changed in version 3.3:版本3.3中更改: Added follow_symlinks argument. Now returns path to the newly created file.Changed in version 3.8:版本3.8中更改: Platform-specific fast-copy syscalls may be used internally in order to copy the file more efficiently. See Platform-dependent efficient copy operations section.
-
shutil.
copy2
(src, dst, *, follow_symlinks=True)¶ Identical to
copy()
except thatcopy2()
also attempts to preserve file metadata.When follow_symlinks is false, and src is a symbolic link,
copy2()
attempts to copy all metadata from the src symbolic link to the newly-created dst symbolic link. However, this functionality is not available on all platforms. On platforms where some or all of this functionality is unavailable,copy2()
will preserve all the metadata it can;copy2()
never raises an exception because it cannot preserve file metadata.copy2()
usescopystat()
to copy the file metadata. Please seecopystat()
for more information about platform support for modifying symbolic link metadata.Raises an auditing event
shutil.copyfile
with argumentssrc
,dst
.Raises an auditing event
shutil.copystat
with argumentssrc
,dst
.Changed in version 3.3:版本3.3中更改: Added follow_symlinks argument, try to copy extended file system attributes too (currently Linux only). Now returns path to the newly created file.Changed in version 3.8:版本3.8中更改: Platform-specific fast-copy syscalls may be used internally in order to copy the file more efficiently. See Platform-dependent efficient copy operations section.
-
shutil.
ignore_patterns
(*patterns)¶ This factory function creates a function that can be used as a callable for
copytree()
's ignore argument, ignoring files and directories that match one of the glob-style patterns provided. See the example below.
-
shutil.
copytree
(src, dst, symlinks=False, ignore=None, copy_function=copy2, ignore_dangling_symlinks=False, dirs_exist_ok=False)¶ Recursively copy an entire directory tree rooted at src to a directory named dst and return the destination directory. All intermediate directories needed to contain dst will also be created by default.
Permissions and times of directories are copied with目录的权限和时间使用copystat()
, individual files are copied usingcopy2()
.copystat()
复制,单个文件使用copystat()
复制。If symlinks is true, symbolic links in the source tree are represented as symbolic links in the new tree and the metadata of the original links will be copied as far as the platform allows; if false or omitted, the contents and metadata of the linked files are copied to the new tree.
When symlinks is false, if the file pointed by the symlink doesn’t exist, an exception will be added in the list of errors raised in an
Error
exception at the end of the copy process. You can set the optional ignore_dangling_symlinks flag to true if you want to silence this exception. Notice that this option has no effect on platforms that don’t supportos.symlink()
.If ignore is given, it must be a callable that will receive as its arguments the directory being visited by
copytree()
, and a list of its contents, as returned byos.listdir()
. Sincecopytree()
is called recursively, the ignore callable will be called once for each directory that is copied. The callable must return a sequence of directory and file names relative to the current directory (i.e. a subset of the items in its second argument); these names will then be ignored in the copy process.ignore_patterns()
can be used to create such a callable that ignores names based on glob-style patterns.If exception(s) occur, an
Error
is raised with a list of reasons.If copy_function is given, it must be a callable that will be used to copy each file. It will be called with the source path and the destination path as arguments. By default,
copy2()
is used, but any function that supports the same signature (likecopy()
) can be used.If dirs_exist_ok is false (the default) and dst already exists, a
FileExistsError
is raised. If dirs_exist_ok is true, the copying operation will continue if it encounters existing directories, and files within the dst tree will be overwritten by corresponding files from the src tree.Raises an auditing event
shutil.copytree
with argumentssrc
,dst
.Changed in version 3.3:版本3.3中更改: Copy metadata when symlinks is false. Now returns dst.Changed in version 3.2:版本3.2中更改: Added the copy_function argument to be able to provide a custom copy function. Added the ignore_dangling_symlinks argument to silence dangling symlinks errors when symlinks is false.Changed in version 3.8:版本3.8中更改: Platform-specific fast-copy syscalls may be used internally in order to copy the file more efficiently. See Platform-dependent efficient copy operations section.New in version 3.8.版本3.8中新增。The dirs_exist_ok parameter.dirs_exist_ok参数。
-
shutil.
rmtree
(path, ignore_errors=False, onerror=None)¶ -
Delete an entire directory tree; path must point to a directory (but not a symbolic link to a directory). If ignore_errors is true, errors resulting from failed removals will be ignored; if false or omitted, such errors are handled by calling a handler specified by onerror or, if that is omitted, they raise an exception.
Note
On platforms that support the necessary fd-based functions a symlink attack resistant version of
rmtree()
is used by default. On other platforms, thermtree()
implementation is susceptible to a symlink attack: given proper timing and circumstances, attackers can manipulate symlinks on the filesystem to delete files they wouldn’t be able to access otherwise. Applications can use thermtree.avoids_symlink_attacks
function attribute to determine which case applies.If onerror is provided, it must be a callable that accepts three parameters: function, path, and excinfo.
The first parameter, function, is the function which raised the exception; it depends on the platform and implementation. The second parameter, path, will be the path name passed to function. The third parameter, excinfo, will be the exception information returned by
sys.exc_info()
. Exceptions raised by onerror will not be caught.Raises an auditing event
shutil.rmtree
with argumentpath
.Changed in version 3.3:版本3.3中更改:Added a symlink attack resistant version that is used automatically if platform supports fd-based functions.添加了一个符号链接抗攻击版本,如果平台支持基于fd的功能,该版本将自动使用。Changed in version 3.8:版本3.8中更改:On Windows, will no longer delete the contents of a directory junction before removing the junction.在Windows上,将不再删除目录连接的内容,然后再删除该连接。-
rmtree.
avoids_symlink_attacks
¶ Indicates whether the current platform and implementation provides a symlink attack resistant version of指示当前平台和实现是否提供rmtree()
.rmtree()
的符号链接抗攻击版本。Currently this is only true for platforms supporting fd-based directory access functions.目前,这仅适用于支持基于fd的目录访问功能的平台。New in version 3.3.版本3.3中新增。
-
-
shutil.
move
(src, dst, copy_function=copy2)¶ Recursively move a file or directory (src) to another location (dst) and return the destination.
If the destination is an existing directory, then src is moved inside that directory. If the destination already exists but is not a directory, it may be overwritten depending on
os.rename()
semantics.If the destination is on the current filesystem, then
os.rename()
is used. Otherwise, src is copied to dst using copy_function and then removed. In case of symlinks, a new symlink pointing to the target of src will be created in or as dst and src will be removed.If copy_function is given, it must be a callable that takes two arguments src and dst, and will be used to copy src to dst if
os.rename()
cannot be used. If the source is a directory,copytree()
is called, passing it thecopy_function()
. The default copy_function iscopy2()
. Usingcopy()
as the copy_function allows the move to succeed when it is not possible to also copy the metadata, at the expense of not copying any of the metadata.Raises an auditing event
shutil.move
with argumentssrc
,dst
.Changed in version 3.3:版本3.3中更改:Added explicit symlink handling for foreign filesystems, thus adapting it to the behavior of GNU’s mv.为外部文件系统添加了显式符号链接处理,从而使其适应GNU mv的行为。Now returns dst.现在返回dst。Changed in version 3.5:版本3.5中更改:Added the copy_function keyword argument.添加了copy_function关键字参数。Changed in version 3.8:版本3.8中更改: Platform-specific fast-copy syscalls may be used internally in order to copy the file more efficiently. See Platform-dependent efficient copy operations section.Changed in version 3.9:版本3.9中更改:Accepts a path-like object for both src and dst.接受src和dst的类路径对象。
-
shutil.
disk_usage
(path)¶ Return disk usage statistics about the given path as a named tuple with the attributes total, used and free, which are the amount of total, used and free space, in bytes. path may be a file or a directory.
New in version 3.3.版本3.3中新增。Changed in version 3.8:版本3.8中更改: On Windows, path can now be a file or directory.Availability: Unix, Windows.
-
shutil.
chown
(path, user=None, group=None)¶ Change owner user and/or group of the given path.
user can be a system user name or a uid; the same applies to group. At least one argument is required.
See also
os.chown()
, the underlying function.Raises an auditing event
shutil.chown
with argumentspath
,user
,group
.Availability: Unix.
New in version 3.3.版本3.3中新增。
-
shutil.
which
(cmd, mode=os.F_OK | os.X_OK, path=None)¶ Return the path to an executable which would be run if the given cmd was called. If no cmd would be called, return
None
.mode is a permission mask passed to
os.access()
, by default determining if the file exists and executable.When no path is specified, the results of
os.environ()
are used, returning either the “PATH” value or a fallback ofos.defpath
.On Windows, the current directory is always prepended to the path whether or not you use the default or provide your own, which is the behavior the command shell uses when finding executables. Additionally, when finding the cmd in the path, the
PATHEXT
environment variable is checked. For example, if you callshutil.which("python")
,which()
will searchPATHEXT
to know that it should look forpython.exe
within the path directories. For example, on Windows:>>> shutil.which("python")
'C:\\Python33\\python.EXE'New in version 3.3.版本3.3中新增。
-
exception
shutil.
Error
¶ This exception collects exceptions that are raised during a multi-file operation.此异常收集在多文件操作期间引发的异常。Forcopytree()
, the exception argument is a list of 3-tuples (srcname, dstname, exception).
Platform-dependent efficient copy operations依赖于平台的高效复制操作¶
Starting from Python 3.8, all functions involving a file copy (copyfile()
, copy()
, copy2()
, copytree()
, and move()
) may use platform-specific “fast-copy” syscalls in order to copy the file more efficiently (see bpo-33671). “fast-copy” means that the copying operation occurs within the kernel, avoiding the use of userspace buffers in Python as in “outfd.write(infd.read())
”.
On macOS fcopyfile is used to copy the file content (not metadata).
On Linux os.sendfile()
is used.
On Windows shutil.copyfile()
uses a bigger default buffer size (1 MiB instead of 64 KiB) and a memoryview()
-based variant of shutil.copyfileobj()
is used.
If the fast-copy operation fails and no data was written in the destination file then shutil will silently fallback on using less efficient 如果快速复制操作失败,并且目标文件中没有写入任何数据,则shutil将在内部使用效率较低的copyfileobj()
function internally.copyfileobj()
函数。
Changed in version 3.8.在版本3.8中更改。
copytree example示例¶
An example that uses the 使用ignore_patterns()
helper:ignore_patterns()
助手的示例:
from shutil import copytree, ignore_patterns
copytree(source, destination, ignore=ignore_patterns('*.pyc', 'tmp*'))
This will copy everything except .pyc
files and files or directories whose name starts with tmp
.
Another example that uses the ignore argument to add a logging call:另一个使用ignore参数添加日志调用的示例:
from shutil import copytree
import logging
def _logpath(path, names):
logging.info('Working in %s', path)
return [] # nothing will be ignored
copytree(source, destination, ignore=_logpath)
rmtree examplermtree示例¶
This example shows how to remove a directory tree on Windows where some of the files have their read-only bit set. 此示例演示如何删除Windows上的目录树,其中一些文件设置了只读位。It uses the onerror callback to clear the readonly bit and reattempt the remove. 它使用OneError回调清除只读位并重新尝试删除。Any subsequent failure will propagate.任何后续故障都将传播。
import os, stat
import shutil
def remove_readonly(func, path, _):
"Clear the readonly bit and reattempt the removal"
os.chmod(path, stat.S_IWRITE)
func(path)
shutil.rmtree(directory, onerror=remove_readonly)
Archiving operations归档操作¶
New in version 3.2.版本3.2中新增。
Changed in version 3.5:版本3.5中更改: Added support for the xztar format.
High-level utilities to create and read compressed and archived files are also provided. 还提供了创建和读取压缩和归档文件的高级实用程序。They rely on the zipfile
and tarfile
modules.
-
shutil.
make_archive
(base_name, format[, root_dir[, base_dir[, verbose[, dry_run[, owner[, group[, logger]]]]]]])¶ Create an archive file (such as zip or tar) and return its name.创建一个存档文件(如zip或tar)并返回其名称。base_name is the name of the file to create, including the path, minus any format-specific extension. format is the archive format: one of “zip” (if the
zlib
module is available), “tar”, “gztar” (if thezlib
module is available), “bztar” (if thebz2
module is available), or “xztar” (if thelzma
module is available).root_dir is a directory that will be the root directory of the archive, all paths in the archive will be relative to it; for example, we typically chdir into root_dir before creating the archive.
base_dir is the directory where we start archiving from; i.e. base_dir will be the common prefix of all files and directories in the archive. base_dir must be given relative to root_dir. See Archiving example with base_dir for how to use base_dir and root_dir together.
root_dir and base_dir both default to the current directory.
If dry_run is true, no archive is created, but the operations that would be executed are logged to logger.如果dry_run为true
,则不会创建存档,但将执行的操作将记录到logger。owner and group are used when creating a tar archive. By default, uses the current owner and group.
logger must be an object compatible with PEP 282, usually an instance of
logging.Logger
.The verbose argument is unused and deprecated.
Raises an auditing event
shutil.make_archive
with argumentsbase_name
,format
,root_dir
,base_dir
.Note
This function is not thread-safe.此函数是非线程安全的。Changed in version 3.8:版本3.8中更改:The modern pax (POSIX.1-2001) format is now used instead of the legacy GNU format for archives created with对于使用format="tar"
.format="tar"
创建的档案,现在使用现代pax(POSIX.1-2001)格式,而不是传统的GNU格式。
-
shutil.
get_archive_formats
()¶ Return a list of supported formats for archiving.返回支持的存档格式列表。Each element of the returned sequence is a tuple返回序列的每个元素都是一个元组(name, description)
.(name, description)
。By default
shutil
provides these formats:zip: ZIP file (if the
zlib
module is available).tar: Uncompressed tar file. Uses POSIX.1-2001 pax format for new archives.
gztar: gzip’ed tar-file (if the
zlib
module is available).bztar: bzip2’ed tar-file (if the
bz2
module is available).xztar: xz’ed tar-file (if the
lzma
module is available).
You can register new formats or provide your own archiver for any existing formats, by using您可以使用register_archive_format()
.register_archive_format()
注册新格式或为任何现有格式提供自己的归档程序。
-
shutil.
register_archive_format
(name, function[, extra_args[, description]])¶ Register an archiver for the format name.为格式name注册归档程序。function
is the callable that will be used to unpack archives.是将用于解包存档的可调用项。The callable will receive the base_name of the file to create, followed by the base_dir (which defaults toos.curdir
) to start archiving from. Further arguments are passed as keyword arguments: owner, group, dry_run and logger (as passed inmake_archive()
).If given, extra_args is a sequence of
(name, value)
pairs that will be used as extra keywords arguments when the archiver callable is used.description is used by
get_archive_formats()
which returns the list of archivers. Defaults to an empty string.
-
shutil.
unregister_archive_format
(name)¶ Remove the archive format name from the list of supported formats.从支持的格式列表中删除存档格式name。
-
shutil.
unpack_archive
(filename[, extract_dir[, format]])¶ Unpack an archive. filename is the full path of the archive.
extract_dir
is the name of the target directory where the archive is unpacked.是解压缩存档文件的目标目录的名称。If not provided, the current working directory is used.如果未提供,则使用当前工作目录。format is the archive format: one of “zip”, “tar”, “gztar”, “bztar”, or “xztar”. Or any other format registered with
register_unpack_format()
. If not provided,unpack_archive()
will use the archive file name extension and see if an unpacker was registered for that extension. In case none is found, aValueError
is raised.Raises an auditing event
shutil.unpack_archive
with argumentsfilename
,extract_dir
,format
.Changed in version 3.7:版本3.7中更改: Accepts a path-like object for filename and extract_dir.
-
shutil.
register_unpack_format
(name, extensions, function[, extra_args[, description]])¶ Registers an unpack format. name is the name of the format and extensions is a list of extensions corresponding to the format, like
.zip
for Zip files.function is the callable that will be used to unpack archives. The callable will receive the path of the archive, followed by the directory the archive must be extracted to.
When provided, extra_args is a sequence of
(name, value)
tuples that will be passed as keywords arguments to the callable.description can be provided to describe the format, and will be returned by the
get_unpack_formats()
function.
-
shutil.
unregister_unpack_format
(name)¶ Unregister an unpack format. name is the name of the format.
-
shutil.
get_unpack_formats
()¶ Return a list of all registered formats for unpacking. Each element of the returned sequence is a tuple
(name, extensions, description)
.By default
shutil
provides these formats:zip
: ZIP file (unpacking compressed files works only if the corresponding module is available).:ZIP文件(仅当相应模块可用时,解包压缩文件才有效)。tar
: uncompressed tar file.:未压缩的tar文件。gztar
: gzip’ed tar-file (if the:gzip'ed tar文件(如果zlib
module is available).zlib
模块可用)。bztar: bzip2’ed tar-file (if the
bz2
module is available).xztar: xz’ed tar-file (if the
lzma
module is available).
You can register new formats or provide your own unpacker for any existing formats, by using您可以使用register_unpack_format()
.register_unpack_format()
注册新格式或为任何现有格式提供自己的解包程序。
Archiving example存档示例¶
In this example, we create a gzip’ed tar-file archive containing all files found in the 在本例中,我们创建了一个gzip的tar文件归档,其中包含在用户的.ssh
directory of the user:.ssh
目录中找到的所有文件:
>>> from shutil import make_archive
>>> import os
>>> archive_name = os.path.expanduser(os.path.join('~', 'myarchive'))
>>> root_dir = os.path.expanduser(os.path.join('~', '.ssh'))
>>> make_archive(archive_name, 'gztar', root_dir)
'/Users/tarek/myarchive.tar.gz'
The resulting archive contains:生成的存档包含:
$ tar -tzvf /Users/tarek/myarchive.tar.gz
drwx------ tarek/staff 0 2010-02-01 16:23:40 ./
-rw-r--r-- tarek/staff 609 2008-06-09 13:26:54 ./authorized_keys
-rwxr-xr-x tarek/staff 65 2008-06-09 13:26:54 ./config
-rwx------ tarek/staff 668 2008-06-09 13:26:54 ./id_dsa
-rwxr-xr-x tarek/staff 609 2008-06-09 13:26:54 ./id_dsa.pub
-rw------- tarek/staff 1675 2008-06-09 13:26:54 ./id_rsa
-rw-r--r-- tarek/staff 397 2008-06-09 13:26:54 ./id_rsa.pub
-rw-r--r-- tarek/staff 37192 2010-02-06 18:23:10 ./known_hosts
Archiving example with base_dir使用base_dir的存档示例¶
In this example, similar to the one above, we show how to use make_archive()
, but this time with the usage of base_dir. We now have the following directory structure:我们现在有以下目录结构:
$ tree tmp
tmp
└── root
└── structure
├── content
└── please_add.txt
└── do_not_add.txt
In the final archive, please_add.txt
should be included, but do_not_add.txt
should not. Therefore we use the following:因此,我们使用以下方法:
>>> from shutil import make_archive
>>> import os
>>> archive_name = os.path.expanduser(os.path.join('~', 'myarchive'))
>>> make_archive(
... archive_name,
... 'tar',
... root_dir='tmp/root',
... base_dir='structure/content',
... )
'/Users/tarek/my_archive.tar'
Listing the files in the resulting archive gives us:在生成的归档文件中列出这些文件可以为我们提供:
$ python -m tarfile -l /Users/tarek/myarchive.tar
structure/content/
structure/content/please_add.txt
Querying the size of the output terminal查询输出终端的大小¶
-
shutil.
get_terminal_size
(fallback=columns, lines)¶ Get the size of the terminal window.获取终端窗口的大小。For each of the two dimensions, the environment variable,对于两个维度中的每个维度,分别检查环境变量COLUMNS
andLINES
respectively, is checked.COLUMNS
和LINES
。If the variable is defined and the value is a positive integer, it is used.如果定义了变量且值为正整数,则使用该变量。When
COLUMNS
orLINES
is not defined, which is the common case, the terminal connected tosys.__stdout__
is queried by invokingos.get_terminal_size()
.If the terminal size cannot be successfully queried, either because the system doesn’t support querying, or because we are not connected to a terminal, the value given in
fallback
parameter is used.fallback
defaults to(80, 24)
which is the default size used by many terminal emulators.The value returned is a named tuple of type
os.terminal_size
.See also: The Single UNIX Specification, Version 2, Other Environment Variables.
New in version 3.3.版本3.3中新增。