doc_content stringlengths 1 386k | doc_id stringlengths 5 188 |
|---|---|
shlex.quote(s)
Return a shell-escaped version of the string s. The returned value is a string that can safely be used as one token in a shell command line, for cases where you cannot use a list. This idiom would be unsafe: >>> filename = 'somefile; rm -rf ~'
>>> command = 'ls -l {}'.format(filename)
>>> print(command) # executed by a shell: boom!
ls -l somefile; rm -rf ~
quote() lets you plug the security hole: >>> from shlex import quote
>>> command = 'ls -l {}'.format(quote(filename))
>>> print(command)
ls -l 'somefile; rm -rf ~'
>>> remote_command = 'ssh home {}'.format(quote(command))
>>> print(remote_command)
ssh home 'ls -l '"'"'somefile; rm -rf ~'"'"''
The quoting is compatible with UNIX shells and with split(): >>> from shlex import split
>>> remote_command = split(remote_command)
>>> remote_command
['ssh', 'home', "ls -l 'somefile; rm -rf ~'"]
>>> command = split(remote_command[-1])
>>> command
['ls', '-l', 'somefile; rm -rf ~']
New in version 3.3. | python.library.shlex#shlex.quote |
class shlex.shlex(instream=None, infile=None, posix=False, punctuation_chars=False)
A shlex instance or subclass instance is a lexical analyzer object. The initialization argument, if present, specifies where to read characters from. It must be a file-/stream-like object with read() and readline() methods, or a string. If no argument is given, input will be taken from sys.stdin. The second optional argument is a filename string, which sets the initial value of the infile attribute. If the instream argument is omitted or equal to sys.stdin, this second argument defaults to “stdin”. The posix argument defines the operational mode: when posix is not true (default), the shlex instance will operate in compatibility mode. When operating in POSIX mode, shlex will try to be as close as possible to the POSIX shell parsing rules. The punctuation_chars argument provides a way to make the behaviour even closer to how real shells parse. This can take a number of values: the default value, False, preserves the behaviour seen under Python 3.5 and earlier. If set to True, then parsing of the characters ();<>|& is changed: any run of these characters (considered punctuation characters) is returned as a single token. If set to a non-empty string of characters, those characters will be used as the punctuation characters. Any characters in the wordchars attribute that appear in punctuation_chars will be removed from wordchars. See Improved Compatibility with Shells for more information. punctuation_chars can be set only upon shlex instance creation and can’t be modified later. Changed in version 3.6: The punctuation_chars parameter was added. | python.library.shlex#shlex.shlex |
shlex.commenters
The string of characters that are recognized as comment beginners. All characters from the comment beginner to end of line are ignored. Includes just '#' by default. | python.library.shlex#shlex.shlex.commenters |
shlex.debug
If this attribute is numeric and 1 or more, a shlex instance will print verbose progress output on its behavior. If you need to use this, you can read the module source code to learn the details. | python.library.shlex#shlex.shlex.debug |
shlex.eof
Token used to determine end of file. This will be set to the empty string (''), in non-POSIX mode, and to None in POSIX mode. | python.library.shlex#shlex.shlex.eof |
shlex.error_leader(infile=None, lineno=None)
This method generates an error message leader in the format of a Unix C compiler error label; the format is '"%s", line %d: ', where the %s is replaced with the name of the current source file and the %d with the current input line number (the optional arguments can be used to override these). This convenience is provided to encourage shlex users to generate error messages in the standard, parseable format understood by Emacs and other Unix tools. | python.library.shlex#shlex.shlex.error_leader |
shlex.escape
Characters that will be considered as escape. This will be only used in POSIX mode, and includes just '\' by default. | python.library.shlex#shlex.shlex.escape |
shlex.escapedquotes
Characters in quotes that will interpret escape characters defined in escape. This is only used in POSIX mode, and includes just '"' by default. | python.library.shlex#shlex.shlex.escapedquotes |
shlex.get_token()
Return a token. If tokens have been stacked using push_token(), pop a token off the stack. Otherwise, read one from the input stream. If reading encounters an immediate end-of-file, eof is returned (the empty string ('') in non-POSIX mode, and None in POSIX mode). | python.library.shlex#shlex.shlex.get_token |
shlex.infile
The name of the current input file, as initially set at class instantiation time or stacked by later source requests. It may be useful to examine this when constructing error messages. | python.library.shlex#shlex.shlex.infile |
shlex.instream
The input stream from which this shlex instance is reading characters. | python.library.shlex#shlex.shlex.instream |
shlex.lineno
Source line number (count of newlines seen so far plus one). | python.library.shlex#shlex.shlex.lineno |
shlex.pop_source()
Pop the last-pushed input source from the input stack. This is the same method used internally when the lexer reaches EOF on a stacked input stream. | python.library.shlex#shlex.shlex.pop_source |
shlex.punctuation_chars
A read-only property. Characters that will be considered punctuation. Runs of punctuation characters will be returned as a single token. However, note that no semantic validity checking will be performed: for example, ‘>>>’ could be returned as a token, even though it may not be recognised as such by shells. New in version 3.6. | python.library.shlex#shlex.shlex.punctuation_chars |
shlex.push_source(newstream, newfile=None)
Push an input source stream onto the input stack. If the filename argument is specified it will later be available for use in error messages. This is the same method used internally by the sourcehook() method. | python.library.shlex#shlex.shlex.push_source |
shlex.push_token(str)
Push the argument onto the token stack. | python.library.shlex#shlex.shlex.push_token |
shlex.quotes
Characters that will be considered string quotes. The token accumulates until the same quote is encountered again (thus, different quote types protect each other as in the shell.) By default, includes ASCII single and double quotes. | python.library.shlex#shlex.shlex.quotes |
shlex.read_token()
Read a raw token. Ignore the pushback stack, and do not interpret source requests. (This is not ordinarily a useful entry point, and is documented here only for the sake of completeness.) | python.library.shlex#shlex.shlex.read_token |
shlex.source
This attribute is None by default. If you assign a string to it, that string will be recognized as a lexical-level inclusion request similar to the source keyword in various shells. That is, the immediately following token will be opened as a filename and input will be taken from that stream until EOF, at which point the close() method of that stream will be called and the input source will again become the original input stream. Source requests may be stacked any number of levels deep. | python.library.shlex#shlex.shlex.source |
shlex.sourcehook(filename)
When shlex detects a source request (see source below) this method is given the following token as argument, and expected to return a tuple consisting of a filename and an open file-like object. Normally, this method first strips any quotes off the argument. If the result is an absolute pathname, or there was no previous source request in effect, or the previous source was a stream (such as sys.stdin), the result is left alone. Otherwise, if the result is a relative pathname, the directory part of the name of the file immediately before it on the source inclusion stack is prepended (this behavior is like the way the C preprocessor handles #include
"file.h"). The result of the manipulations is treated as a filename, and returned as the first component of the tuple, with open() called on it to yield the second component. (Note: this is the reverse of the order of arguments in instance initialization!) This hook is exposed so that you can use it to implement directory search paths, addition of file extensions, and other namespace hacks. There is no corresponding ‘close’ hook, but a shlex instance will call the close() method of the sourced input stream when it returns EOF. For more explicit control of source stacking, use the push_source() and pop_source() methods. | python.library.shlex#shlex.shlex.sourcehook |
shlex.token
The token buffer. It may be useful to examine this when catching exceptions. | python.library.shlex#shlex.shlex.token |
shlex.whitespace
Characters that will be considered whitespace and skipped. Whitespace bounds tokens. By default, includes space, tab, linefeed and carriage-return. | python.library.shlex#shlex.shlex.whitespace |
shlex.whitespace_split
If True, tokens will only be split in whitespaces. This is useful, for example, for parsing command lines with shlex, getting tokens in a similar way to shell arguments. When used in combination with punctuation_chars, tokens will be split on whitespace in addition to those characters. Changed in version 3.8: The punctuation_chars attribute was made compatible with the whitespace_split attribute. | python.library.shlex#shlex.shlex.whitespace_split |
shlex.wordchars
The string of characters that will accumulate into multi-character tokens. By default, includes all ASCII alphanumerics and underscore. In POSIX mode, the accented characters in the Latin-1 set are also included. If punctuation_chars is not empty, the characters ~-./*?=, which can appear in filename specifications and command line parameters, will also be included in this attribute, and any characters which appear in punctuation_chars will be removed from wordchars if they are present there. If whitespace_split is set to True, this will have no effect. | python.library.shlex#shlex.shlex.wordchars |
shlex.split(s, comments=False, posix=True)
Split the string s using shell-like syntax. If comments is False (the default), the parsing of comments in the given string will be disabled (setting the commenters attribute of the shlex instance to the empty string). This function operates in POSIX mode by default, but uses non-POSIX mode if the posix argument is false. Note Since the split() function instantiates a shlex instance, passing None for s will read the string to split from standard input. Deprecated since version 3.9: Passing None for s will raise an exception in future Python versions. | python.library.shlex#shlex.split |
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. In particular, functions are provided which support file copying and removal. For operations on individual files, see also the os module. Warning Even the higher-level file copying functions (shutil.copy(), shutil.copy2()) cannot copy all file metadata. On POSIX platforms, this means that file owner and group are lost as well as ACLs. On Mac OS, the resource fork and other metadata are not used. 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. Directory and files operations
shutil.copyfileobj(fsrc, fdst[, length])
Copy the contents of the file-like object fsrc to the file-like object fdst. The integer length, if given, is the buffer size. 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. 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.
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 and dst are path-like objects or path names given as strings. dst must be the complete target file name; look at copy() for a copy that accepts a target directory path. If src and dst specify the same file, SameFileError is raised. The destination location must be writable; otherwise, an OSError exception will be raised. If dst already exists, it will be replaced. 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. Raises an auditing event shutil.copyfile with arguments src, dst. Changed in version 3.3: IOError used to be raised instead of OSError. Added follow_symlinks argument. Now returns dst. Changed in version 3.4: Raise SameFileError instead of Error. Since the former is a subclass of the latter, this change is backward compatible. Changed in version 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. New in version 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 see copystat() for more information. If copymode() 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 shutil.copymode with arguments src, dst. Changed in version 3.3: Added follow_symlinks argument.
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. 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. If os.chmod in os.supports_follow_symlinks is True, copystat() can modify the permission bits of a symbolic link. If os.utime in os.supports_follow_symlinks is True, copystat() can modify the last access and modification times of a symbolic link. If os.chflags in os.supports_follow_symlinks is True, 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. Raises an auditing event shutil.copystat with arguments src, dst. Changed in version 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 (see os.chmod()). Other metadata, like the file’s creation and modification times, is not preserved. To preserve all file metadata from the original, use copy2() instead. Raises an auditing event shutil.copyfile with arguments src, dst. Raises an auditing event shutil.copymode with arguments src, dst. Changed in version 3.3: Added follow_symlinks argument. Now returns path to the newly created file. Changed in version 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 that copy2() 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() uses copystat() to copy the file metadata. Please see copystat() for more information about platform support for modifying symbolic link metadata. Raises an auditing event shutil.copyfile with arguments src, dst. Raises an auditing event shutil.copystat with arguments src, dst. Changed in version 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: 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. dirs_exist_ok dictates whether to raise an exception in case dst or any missing parent directory already exists. Permissions and times of directories are copied with copystat(), individual files are copied using copy2(). 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 support os.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 by os.listdir(). Since copytree() 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 (like copy()) can be used. Raises an auditing event shutil.copytree with arguments src, dst. Changed in version 3.3: Copy metadata when symlinks is false. Now returns dst. Changed in version 3.2: Added the copy_function argument to be able to provide a custom copy function. Added the ignore_dangling_symlinks argument to silent dangling symlinks errors when symlinks is false. Changed in version 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: The dirs_exist_ok parameter.
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, the rmtree() 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 the rmtree.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 argument path. Changed in version 3.3: Added a symlink attack resistant version that is used automatically if platform supports fd-based functions. Changed in version 3.8: On Windows, will no longer delete the contents of a directory junction before removing the junction.
rmtree.avoids_symlink_attacks
Indicates whether the current platform and implementation provides a symlink attack resistant version of rmtree(). Currently this is only true for platforms supporting fd-based directory access functions. New in version 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 the copy_function(). The default copy_function is copy2(). Using copy() 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 arguments src, dst. Changed in version 3.3: Added explicit symlink handling for foreign filesystems, thus adapting it to the behavior of GNU’s mv. Now returns dst. Changed in version 3.5: Added the copy_function keyword argument. Changed in version 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: Accepts a path-like object for both src and 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. Changed in version 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 arguments path, user, group. Availability: Unix. New in version 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 of os.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 call shutil.which("python"), which() will search PATHEXT to know that it should look for python.exe within the path directories. For example, on Windows: >>> shutil.which("python")
'C:\\Python33\\python.EXE'
New in version 3.3. Changed in version 3.8: The bytes type is now accepted. If cmd type is bytes, the result type is also bytes.
exception shutil.Error
This exception collects exceptions that are raised during a multi-file operation. For copytree(), 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 copyfileobj() function internally. Changed in version 3.8. copytree example This example is the implementation of the copytree() function, described above, with the docstring omitted. It demonstrates many of the other functions provided by this module. def copytree(src, dst, symlinks=False):
names = os.listdir(src)
os.makedirs(dst)
errors = []
for name in names:
srcname = os.path.join(src, name)
dstname = os.path.join(dst, name)
try:
if symlinks and os.path.islink(srcname):
linkto = os.readlink(srcname)
os.symlink(linkto, dstname)
elif os.path.isdir(srcname):
copytree(srcname, dstname, symlinks)
else:
copy2(srcname, dstname)
# XXX What about devices, sockets etc.?
except OSError as why:
errors.append((srcname, dstname, str(why)))
# catch the Error from the recursive copytree so that we can
# continue with other files
except Error as err:
errors.extend(err.args[0])
try:
copystat(src, dst)
except OSError as why:
# can't copy file access times on Windows
if why.winerror is None:
errors.extend((src, dst, str(why)))
if errors:
raise Error(errors)
Another example that uses the ignore_patterns() helper: 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: 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 example This example shows how to remove a directory tree on Windows where some of the files have their read-only bit set. It uses the onerror callback to clear the readonly bit and reattempt the remove. 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. Changed in version 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. 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 the zlib module is available), “bztar” (if the bz2 module is available), or “xztar” (if the lzma 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. 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 arguments base_name, format, root_dir, base_dir. Changed in version 3.8: The modern pax (POSIX.1-2001) format is now used instead of the legacy GNU format for archives created with format="tar".
shutil.get_archive_formats()
Return a list of supported formats for archiving. Each element of the returned sequence is a tuple (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().
shutil.register_archive_format(name, function[, extra_args[, description]])
Register an archiver for the format 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 to os.curdir) to start archiving from. Further arguments are passed as keyword arguments: owner, group, dry_run and logger (as passed in make_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.
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, a ValueError is raised. Raises an auditing event shutil.unpack_archive with arguments filename, extract_dir, format. Changed in version 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).
tar: uncompressed tar file.
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 unpacker for any existing formats, by using register_unpack_format().
Archiving example In this example, we create a gzip’ed tar-file archive containing all files found in the .ssh directory of the user: >>> 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
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 and LINES respectively, is checked. If the variable is defined and the value is a positive integer, it is used. When COLUMNS or LINES is not defined, which is the common case, the terminal connected to sys.__stdout__ is queried by invoking os.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. | python.library.shutil |
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 arguments path, user, group. Availability: Unix. New in version 3.3. | python.library.shutil#shutil.chown |
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 (see os.chmod()). Other metadata, like the file’s creation and modification times, is not preserved. To preserve all file metadata from the original, use copy2() instead. Raises an auditing event shutil.copyfile with arguments src, dst. Raises an auditing event shutil.copymode with arguments src, dst. Changed in version 3.3: Added follow_symlinks argument. Now returns path to the newly created file. Changed in version 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. | python.library.shutil#shutil.copy |
shutil.copy2(src, dst, *, follow_symlinks=True)
Identical to copy() except that copy2() 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() uses copystat() to copy the file metadata. Please see copystat() for more information about platform support for modifying symbolic link metadata. Raises an auditing event shutil.copyfile with arguments src, dst. Raises an auditing event shutil.copystat with arguments src, dst. Changed in version 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: Platform-specific fast-copy syscalls may be used internally in order to copy the file more efficiently. See Platform-dependent efficient copy operations section. | python.library.shutil#shutil.copy2 |
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 and dst are path-like objects or path names given as strings. dst must be the complete target file name; look at copy() for a copy that accepts a target directory path. If src and dst specify the same file, SameFileError is raised. The destination location must be writable; otherwise, an OSError exception will be raised. If dst already exists, it will be replaced. 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. Raises an auditing event shutil.copyfile with arguments src, dst. Changed in version 3.3: IOError used to be raised instead of OSError. Added follow_symlinks argument. Now returns dst. Changed in version 3.4: Raise SameFileError instead of Error. Since the former is a subclass of the latter, this change is backward compatible. Changed in version 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. | python.library.shutil#shutil.copyfile |
shutil.copyfileobj(fsrc, fdst[, length])
Copy the contents of the file-like object fsrc to the file-like object fdst. The integer length, if given, is the buffer size. 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. 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. | python.library.shutil#shutil.copyfileobj |
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 see copystat() for more information. If copymode() 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 shutil.copymode with arguments src, dst. Changed in version 3.3: Added follow_symlinks argument. | python.library.shutil#shutil.copymode |
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. 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. If os.chmod in os.supports_follow_symlinks is True, copystat() can modify the permission bits of a symbolic link. If os.utime in os.supports_follow_symlinks is True, copystat() can modify the last access and modification times of a symbolic link. If os.chflags in os.supports_follow_symlinks is True, 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. Raises an auditing event shutil.copystat with arguments src, dst. Changed in version 3.3: Added follow_symlinks argument and support for Linux extended attributes. | python.library.shutil#shutil.copystat |
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. dirs_exist_ok dictates whether to raise an exception in case dst or any missing parent directory already exists. Permissions and times of directories are copied with copystat(), individual files are copied using copy2(). 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 support os.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 by os.listdir(). Since copytree() 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 (like copy()) can be used. Raises an auditing event shutil.copytree with arguments src, dst. Changed in version 3.3: Copy metadata when symlinks is false. Now returns dst. Changed in version 3.2: Added the copy_function argument to be able to provide a custom copy function. Added the ignore_dangling_symlinks argument to silent dangling symlinks errors when symlinks is false. Changed in version 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: The dirs_exist_ok parameter. | python.library.shutil#shutil.copytree |
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. Changed in version 3.8: On Windows, path can now be a file or directory. Availability: Unix, Windows. | python.library.shutil#shutil.disk_usage |
exception shutil.Error
This exception collects exceptions that are raised during a multi-file operation. For copytree(), the exception argument is a list of 3-tuples (srcname, dstname, exception). | python.library.shutil#shutil.Error |
shutil.get_archive_formats()
Return a list of supported formats for archiving. Each element of the returned sequence is a tuple (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(). | python.library.shutil#shutil.get_archive_formats |
shutil.get_terminal_size(fallback=(columns, lines))
Get the size of the terminal window. For each of the two dimensions, the environment variable, COLUMNS and LINES respectively, is checked. If the variable is defined and the value is a positive integer, it is used. When COLUMNS or LINES is not defined, which is the common case, the terminal connected to sys.__stdout__ is queried by invoking os.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. | python.library.shutil#shutil.get_terminal_size |
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).
tar: uncompressed tar file.
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 unpacker for any existing formats, by using register_unpack_format(). | python.library.shutil#shutil.get_unpack_formats |
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. | python.library.shutil#shutil.ignore_patterns |
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. 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 the zlib module is available), “bztar” (if the bz2 module is available), or “xztar” (if the lzma 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. 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 arguments base_name, format, root_dir, base_dir. Changed in version 3.8: The modern pax (POSIX.1-2001) format is now used instead of the legacy GNU format for archives created with format="tar". | python.library.shutil#shutil.make_archive |
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 the copy_function(). The default copy_function is copy2(). Using copy() 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 arguments src, dst. Changed in version 3.3: Added explicit symlink handling for foreign filesystems, thus adapting it to the behavior of GNU’s mv. Now returns dst. Changed in version 3.5: Added the copy_function keyword argument. Changed in version 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: Accepts a path-like object for both src and dst. | python.library.shutil#shutil.move |
shutil.register_archive_format(name, function[, extra_args[, description]])
Register an archiver for the format 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 to os.curdir) to start archiving from. Further arguments are passed as keyword arguments: owner, group, dry_run and logger (as passed in make_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. | python.library.shutil#shutil.register_archive_format |
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. | python.library.shutil#shutil.register_unpack_format |
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, the rmtree() 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 the rmtree.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 argument path. Changed in version 3.3: Added a symlink attack resistant version that is used automatically if platform supports fd-based functions. Changed in version 3.8: On Windows, will no longer delete the contents of a directory junction before removing the junction.
rmtree.avoids_symlink_attacks
Indicates whether the current platform and implementation provides a symlink attack resistant version of rmtree(). Currently this is only true for platforms supporting fd-based directory access functions. New in version 3.3. | python.library.shutil#shutil.rmtree |
rmtree.avoids_symlink_attacks
Indicates whether the current platform and implementation provides a symlink attack resistant version of rmtree(). Currently this is only true for platforms supporting fd-based directory access functions. New in version 3.3. | python.library.shutil#shutil.rmtree.avoids_symlink_attacks |
exception shutil.SameFileError
This exception is raised if source and destination in copyfile() are the same file. New in version 3.4. | python.library.shutil#shutil.SameFileError |
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, a ValueError is raised. Raises an auditing event shutil.unpack_archive with arguments filename, extract_dir, format. Changed in version 3.7: Accepts a path-like object for filename and extract_dir. | python.library.shutil#shutil.unpack_archive |
shutil.unregister_archive_format(name)
Remove the archive format name from the list of supported formats. | python.library.shutil#shutil.unregister_archive_format |
shutil.unregister_unpack_format(name)
Unregister an unpack format. name is the name of the format. | python.library.shutil#shutil.unregister_unpack_format |
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 of os.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 call shutil.which("python"), which() will search PATHEXT to know that it should look for python.exe within the path directories. For example, on Windows: >>> shutil.which("python")
'C:\\Python33\\python.EXE'
New in version 3.3. Changed in version 3.8: The bytes type is now accepted. If cmd type is bytes, the result type is also bytes. | python.library.shutil#shutil.which |
signal — Set handlers for asynchronous events This module provides mechanisms to use signal handlers in Python. General rules The signal.signal() function allows defining custom handlers to be executed when a signal is received. A small number of default handlers are installed: SIGPIPE is ignored (so write errors on pipes and sockets can be reported as ordinary Python exceptions) and SIGINT is translated into a KeyboardInterrupt exception if the parent process has not changed it. A handler for a particular signal, once set, remains installed until it is explicitly reset (Python emulates the BSD style interface regardless of the underlying implementation), with the exception of the handler for SIGCHLD, which follows the underlying implementation. Execution of Python signal handlers A Python signal handler does not get executed inside the low-level (C) signal handler. Instead, the low-level signal handler sets a flag which tells the virtual machine to execute the corresponding Python signal handler at a later point(for example at the next bytecode instruction). This has consequences: It makes little sense to catch synchronous errors like SIGFPE or SIGSEGV that are caused by an invalid operation in C code. Python will return from the signal handler to the C code, which is likely to raise the same signal again, causing Python to apparently hang. From Python 3.3 onwards, you can use the faulthandler module to report on synchronous errors. A long-running calculation implemented purely in C (such as regular expression matching on a large body of text) may run uninterrupted for an arbitrary amount of time, regardless of any signals received. The Python signal handlers will be called when the calculation finishes. Signals and threads Python signal handlers are always executed in the main Python thread of the main interpreter, even if the signal was received in another thread. This means that signals can’t be used as a means of inter-thread communication. You can use the synchronization primitives from the threading module instead. Besides, only the main thread of the main interpreter is allowed to set a new signal handler. Module contents Changed in version 3.5: signal (SIG*), handler (SIG_DFL, SIG_IGN) and sigmask (SIG_BLOCK, SIG_UNBLOCK, SIG_SETMASK) related constants listed below were turned into enums. getsignal(), pthread_sigmask(), sigpending() and sigwait() functions return human-readable enums. The variables defined in the signal module are:
signal.SIG_DFL
This is one of two standard signal handling options; it will simply perform the default function for the signal. For example, on most systems the default action for SIGQUIT is to dump core and exit, while the default action for SIGCHLD is to simply ignore it.
signal.SIG_IGN
This is another standard signal handler, which will simply ignore the given signal.
signal.SIGABRT
Abort signal from abort(3).
signal.SIGALRM
Timer signal from alarm(2). Availability: Unix.
signal.SIGBREAK
Interrupt from keyboard (CTRL + BREAK). Availability: Windows.
signal.SIGBUS
Bus error (bad memory access). Availability: Unix.
signal.SIGCHLD
Child process stopped or terminated. Availability: Unix.
signal.SIGCLD
Alias to SIGCHLD.
signal.SIGCONT
Continue the process if it is currently stopped Availability: Unix.
signal.SIGFPE
Floating-point exception. For example, division by zero. See also ZeroDivisionError is raised when the second argument of a division or modulo operation is zero.
signal.SIGHUP
Hangup detected on controlling terminal or death of controlling process. Availability: Unix.
signal.SIGILL
Illegal instruction.
signal.SIGINT
Interrupt from keyboard (CTRL + C). Default action is to raise KeyboardInterrupt.
signal.SIGKILL
Kill signal. It cannot be caught, blocked, or ignored. Availability: Unix.
signal.SIGPIPE
Broken pipe: write to pipe with no readers. Default action is to ignore the signal. Availability: Unix.
signal.SIGSEGV
Segmentation fault: invalid memory reference.
signal.SIGTERM
Termination signal.
signal.SIGUSR1
User-defined signal 1. Availability: Unix.
signal.SIGUSR2
User-defined signal 2. Availability: Unix.
signal.SIGWINCH
Window resize signal. Availability: Unix.
SIG*
All the signal numbers are defined symbolically. For example, the hangup signal is defined as signal.SIGHUP; the variable names are identical to the names used in C programs, as found in <signal.h>. The Unix man page for ‘signal()’ lists the existing signals (on some systems this is signal(2), on others the list is in signal(7)). Note that not all systems define the same set of signal names; only those names defined by the system are defined by this module.
signal.CTRL_C_EVENT
The signal corresponding to the Ctrl+C keystroke event. This signal can only be used with os.kill(). Availability: Windows. New in version 3.2.
signal.CTRL_BREAK_EVENT
The signal corresponding to the Ctrl+Break keystroke event. This signal can only be used with os.kill(). Availability: Windows. New in version 3.2.
signal.NSIG
One more than the number of the highest signal number.
signal.ITIMER_REAL
Decrements interval timer in real time, and delivers SIGALRM upon expiration.
signal.ITIMER_VIRTUAL
Decrements interval timer only when the process is executing, and delivers SIGVTALRM upon expiration.
signal.ITIMER_PROF
Decrements interval timer both when the process executes and when the system is executing on behalf of the process. Coupled with ITIMER_VIRTUAL, this timer is usually used to profile the time spent by the application in user and kernel space. SIGPROF is delivered upon expiration.
signal.SIG_BLOCK
A possible value for the how parameter to pthread_sigmask() indicating that signals are to be blocked. New in version 3.3.
signal.SIG_UNBLOCK
A possible value for the how parameter to pthread_sigmask() indicating that signals are to be unblocked. New in version 3.3.
signal.SIG_SETMASK
A possible value for the how parameter to pthread_sigmask() indicating that the signal mask is to be replaced. New in version 3.3.
The signal module defines one exception:
exception signal.ItimerError
Raised to signal an error from the underlying setitimer() or getitimer() implementation. Expect this error if an invalid interval timer or a negative time is passed to setitimer(). This error is a subtype of OSError. New in version 3.3: This error used to be a subtype of IOError, which is now an alias of OSError.
The signal module defines the following functions:
signal.alarm(time)
If time is non-zero, this function requests that a SIGALRM signal be sent to the process in time seconds. Any previously scheduled alarm is canceled (only one alarm can be scheduled at any time). The returned value is then the number of seconds before any previously set alarm was to have been delivered. If time is zero, no alarm is scheduled, and any scheduled alarm is canceled. If the return value is zero, no alarm is currently scheduled. Availability: Unix. See the man page alarm(2) for further information.
signal.getsignal(signalnum)
Return the current signal handler for the signal signalnum. The returned value may be a callable Python object, or one of the special values signal.SIG_IGN, signal.SIG_DFL or None. Here, signal.SIG_IGN means that the signal was previously ignored, signal.SIG_DFL means that the default way of handling the signal was previously in use, and None means that the previous signal handler was not installed from Python.
signal.strsignal(signalnum)
Return the system description of the signal signalnum, such as “Interrupt”, “Segmentation fault”, etc. Returns None if the signal is not recognized. New in version 3.8.
signal.valid_signals()
Return the set of valid signal numbers on this platform. This can be less than range(1, NSIG) if some signals are reserved by the system for internal use. New in version 3.8.
signal.pause()
Cause the process to sleep until a signal is received; the appropriate handler will then be called. Returns nothing. Availability: Unix. See the man page signal(2) for further information. See also sigwait(), sigwaitinfo(), sigtimedwait() and sigpending().
signal.raise_signal(signum)
Sends a signal to the calling process. Returns nothing. New in version 3.8.
signal.pidfd_send_signal(pidfd, sig, siginfo=None, flags=0)
Send signal sig to the process referred to by file descriptor pidfd. Python does not currently support the siginfo parameter; it must be None. The flags argument is provided for future extensions; no flag values are currently defined. See the pidfd_send_signal(2) man page for more information. Availability: Linux 5.1+ New in version 3.9.
signal.pthread_kill(thread_id, signalnum)
Send the signal signalnum to the thread thread_id, another thread in the same process as the caller. The target thread can be executing any code (Python or not). However, if the target thread is executing the Python interpreter, the Python signal handlers will be executed by the main thread of the main interpreter. Therefore, the only point of sending a signal to a particular Python thread would be to force a running system call to fail with InterruptedError. Use threading.get_ident() or the ident attribute of threading.Thread objects to get a suitable value for thread_id. If signalnum is 0, then no signal is sent, but error checking is still performed; this can be used to check if the target thread is still running. Raises an auditing event signal.pthread_kill with arguments thread_id, signalnum. Availability: Unix. See the man page pthread_kill(3) for further information. See also os.kill(). New in version 3.3.
signal.pthread_sigmask(how, mask)
Fetch and/or change the signal mask of the calling thread. The signal mask is the set of signals whose delivery is currently blocked for the caller. Return the old signal mask as a set of signals. The behavior of the call is dependent on the value of how, as follows.
SIG_BLOCK: The set of blocked signals is the union of the current set and the mask argument.
SIG_UNBLOCK: The signals in mask are removed from the current set of blocked signals. It is permissible to attempt to unblock a signal which is not blocked.
SIG_SETMASK: The set of blocked signals is set to the mask argument. mask is a set of signal numbers (e.g. {signal.SIGINT, signal.SIGTERM}). Use valid_signals() for a full mask including all signals. For example, signal.pthread_sigmask(signal.SIG_BLOCK, []) reads the signal mask of the calling thread. SIGKILL and SIGSTOP cannot be blocked. Availability: Unix. See the man page sigprocmask(3) and pthread_sigmask(3) for further information. See also pause(), sigpending() and sigwait(). New in version 3.3.
signal.setitimer(which, seconds, interval=0.0)
Sets given interval timer (one of signal.ITIMER_REAL, signal.ITIMER_VIRTUAL or signal.ITIMER_PROF) specified by which to fire after seconds (float is accepted, different from alarm()) and after that every interval seconds (if interval is non-zero). The interval timer specified by which can be cleared by setting seconds to zero. When an interval timer fires, a signal is sent to the process. The signal sent is dependent on the timer being used; signal.ITIMER_REAL will deliver SIGALRM, signal.ITIMER_VIRTUAL sends SIGVTALRM, and signal.ITIMER_PROF will deliver SIGPROF. The old values are returned as a tuple: (delay, interval). Attempting to pass an invalid interval timer will cause an ItimerError. Availability: Unix.
signal.getitimer(which)
Returns current value of a given interval timer specified by which. Availability: Unix.
signal.set_wakeup_fd(fd, *, warn_on_full_buffer=True)
Set the wakeup file descriptor to fd. When a signal is received, the signal number is written as a single byte into the fd. This can be used by a library to wakeup a poll or select call, allowing the signal to be fully processed. The old wakeup fd is returned (or -1 if file descriptor wakeup was not enabled). If fd is -1, file descriptor wakeup is disabled. If not -1, fd must be non-blocking. It is up to the library to remove any bytes from fd before calling poll or select again. When threads are enabled, this function can only be called from the main thread of the main interpreter; attempting to call it from other threads will cause a ValueError exception to be raised. There are two common ways to use this function. In both approaches, you use the fd to wake up when a signal arrives, but then they differ in how they determine which signal or signals have arrived. In the first approach, we read the data out of the fd’s buffer, and the byte values give you the signal numbers. This is simple, but in rare cases it can run into a problem: generally the fd will have a limited amount of buffer space, and if too many signals arrive too quickly, then the buffer may become full, and some signals may be lost. If you use this approach, then you should set warn_on_full_buffer=True, which will at least cause a warning to be printed to stderr when signals are lost. In the second approach, we use the wakeup fd only for wakeups, and ignore the actual byte values. In this case, all we care about is whether the fd’s buffer is empty or non-empty; a full buffer doesn’t indicate a problem at all. If you use this approach, then you should set warn_on_full_buffer=False, so that your users are not confused by spurious warning messages. Changed in version 3.5: On Windows, the function now also supports socket handles. Changed in version 3.7: Added warn_on_full_buffer parameter.
signal.siginterrupt(signalnum, flag)
Change system call restart behaviour: if flag is False, system calls will be restarted when interrupted by signal signalnum, otherwise system calls will be interrupted. Returns nothing. Availability: Unix. See the man page siginterrupt(3) for further information. Note that installing a signal handler with signal() will reset the restart behaviour to interruptible by implicitly calling siginterrupt() with a true flag value for the given signal.
signal.signal(signalnum, handler)
Set the handler for signal signalnum to the function handler. handler can be a callable Python object taking two arguments (see below), or one of the special values signal.SIG_IGN or signal.SIG_DFL. The previous signal handler will be returned (see the description of getsignal() above). (See the Unix man page signal(2) for further information.) When threads are enabled, this function can only be called from the main thread of the main interpreter; attempting to call it from other threads will cause a ValueError exception to be raised. The handler is called with two arguments: the signal number and the current stack frame (None or a frame object; for a description of frame objects, see the description in the type hierarchy or see the attribute descriptions in the inspect module). On Windows, signal() can only be called with SIGABRT, SIGFPE, SIGILL, SIGINT, SIGSEGV, SIGTERM, or SIGBREAK. A ValueError will be raised in any other case. Note that not all systems define the same set of signal names; an AttributeError will be raised if a signal name is not defined as SIG* module level constant.
signal.sigpending()
Examine the set of signals that are pending for delivery to the calling thread (i.e., the signals which have been raised while blocked). Return the set of the pending signals. Availability: Unix. See the man page sigpending(2) for further information. See also pause(), pthread_sigmask() and sigwait(). New in version 3.3.
signal.sigwait(sigset)
Suspend execution of the calling thread until the delivery of one of the signals specified in the signal set sigset. The function accepts the signal (removes it from the pending list of signals), and returns the signal number. Availability: Unix. See the man page sigwait(3) for further information. See also pause(), pthread_sigmask(), sigpending(), sigwaitinfo() and sigtimedwait(). New in version 3.3.
signal.sigwaitinfo(sigset)
Suspend execution of the calling thread until the delivery of one of the signals specified in the signal set sigset. The function accepts the signal and removes it from the pending list of signals. If one of the signals in sigset is already pending for the calling thread, the function will return immediately with information about that signal. The signal handler is not called for the delivered signal. The function raises an InterruptedError if it is interrupted by a signal that is not in sigset. The return value is an object representing the data contained in the siginfo_t structure, namely: si_signo, si_code, si_errno, si_pid, si_uid, si_status, si_band. Availability: Unix. See the man page sigwaitinfo(2) for further information. See also pause(), sigwait() and sigtimedwait(). New in version 3.3. Changed in version 3.5: The function is now retried if interrupted by a signal not in sigset and the signal handler does not raise an exception (see PEP 475 for the rationale).
signal.sigtimedwait(sigset, timeout)
Like sigwaitinfo(), but takes an additional timeout argument specifying a timeout. If timeout is specified as 0, a poll is performed. Returns None if a timeout occurs. Availability: Unix. See the man page sigtimedwait(2) for further information. See also pause(), sigwait() and sigwaitinfo(). New in version 3.3. Changed in version 3.5: The function is now retried with the recomputed timeout if interrupted by a signal not in sigset and the signal handler does not raise an exception (see PEP 475 for the rationale).
Example Here is a minimal example program. It uses the alarm() function to limit the time spent waiting to open a file; this is useful if the file is for a serial device that may not be turned on, which would normally cause the os.open() to hang indefinitely. The solution is to set a 5-second alarm before opening the file; if the operation takes too long, the alarm signal will be sent, and the handler raises an exception. import signal, os
def handler(signum, frame):
print('Signal handler called with signal', signum)
raise OSError("Couldn't open device!")
# Set the signal handler and a 5-second alarm
signal.signal(signal.SIGALRM, handler)
signal.alarm(5)
# This open() may hang indefinitely
fd = os.open('/dev/ttyS0', os.O_RDWR)
signal.alarm(0) # Disable the alarm
Note on SIGPIPE Piping output of your program to tools like head(1) will cause a SIGPIPE signal to be sent to your process when the receiver of its standard output closes early. This results in an exception like BrokenPipeError: [Errno 32] Broken pipe. To handle this case, wrap your entry point to catch this exception as follows: import os
import sys
def main():
try:
# simulate large output (your code replaces this loop)
for x in range(10000):
print("y")
# flush output here to force SIGPIPE to be triggered
# while inside this try block.
sys.stdout.flush()
except BrokenPipeError:
# Python flushes standard streams on exit; redirect remaining output
# to devnull to avoid another BrokenPipeError at shutdown
devnull = os.open(os.devnull, os.O_WRONLY)
os.dup2(devnull, sys.stdout.fileno())
sys.exit(1) # Python exits with error code 1 on EPIPE
if __name__ == '__main__':
main()
Do not set SIGPIPE’s disposition to SIG_DFL in order to avoid BrokenPipeError. Doing that would cause your program to exit unexpectedly also whenever any socket connection is interrupted while your program is still writing to it. | python.library.signal |
signal.alarm(time)
If time is non-zero, this function requests that a SIGALRM signal be sent to the process in time seconds. Any previously scheduled alarm is canceled (only one alarm can be scheduled at any time). The returned value is then the number of seconds before any previously set alarm was to have been delivered. If time is zero, no alarm is scheduled, and any scheduled alarm is canceled. If the return value is zero, no alarm is currently scheduled. Availability: Unix. See the man page alarm(2) for further information. | python.library.signal#signal.alarm |
signal.CTRL_BREAK_EVENT
The signal corresponding to the Ctrl+Break keystroke event. This signal can only be used with os.kill(). Availability: Windows. New in version 3.2. | python.library.signal#signal.CTRL_BREAK_EVENT |
signal.CTRL_C_EVENT
The signal corresponding to the Ctrl+C keystroke event. This signal can only be used with os.kill(). Availability: Windows. New in version 3.2. | python.library.signal#signal.CTRL_C_EVENT |
signal.getitimer(which)
Returns current value of a given interval timer specified by which. Availability: Unix. | python.library.signal#signal.getitimer |
signal.getsignal(signalnum)
Return the current signal handler for the signal signalnum. The returned value may be a callable Python object, or one of the special values signal.SIG_IGN, signal.SIG_DFL or None. Here, signal.SIG_IGN means that the signal was previously ignored, signal.SIG_DFL means that the default way of handling the signal was previously in use, and None means that the previous signal handler was not installed from Python. | python.library.signal#signal.getsignal |
exception signal.ItimerError
Raised to signal an error from the underlying setitimer() or getitimer() implementation. Expect this error if an invalid interval timer or a negative time is passed to setitimer(). This error is a subtype of OSError. New in version 3.3: This error used to be a subtype of IOError, which is now an alias of OSError. | python.library.signal#signal.ItimerError |
signal.ITIMER_PROF
Decrements interval timer both when the process executes and when the system is executing on behalf of the process. Coupled with ITIMER_VIRTUAL, this timer is usually used to profile the time spent by the application in user and kernel space. SIGPROF is delivered upon expiration. | python.library.signal#signal.ITIMER_PROF |
signal.ITIMER_REAL
Decrements interval timer in real time, and delivers SIGALRM upon expiration. | python.library.signal#signal.ITIMER_REAL |
signal.ITIMER_VIRTUAL
Decrements interval timer only when the process is executing, and delivers SIGVTALRM upon expiration. | python.library.signal#signal.ITIMER_VIRTUAL |
signal.NSIG
One more than the number of the highest signal number. | python.library.signal#signal.NSIG |
signal.pause()
Cause the process to sleep until a signal is received; the appropriate handler will then be called. Returns nothing. Availability: Unix. See the man page signal(2) for further information. See also sigwait(), sigwaitinfo(), sigtimedwait() and sigpending(). | python.library.signal#signal.pause |
signal.pidfd_send_signal(pidfd, sig, siginfo=None, flags=0)
Send signal sig to the process referred to by file descriptor pidfd. Python does not currently support the siginfo parameter; it must be None. The flags argument is provided for future extensions; no flag values are currently defined. See the pidfd_send_signal(2) man page for more information. Availability: Linux 5.1+ New in version 3.9. | python.library.signal#signal.pidfd_send_signal |
signal.pthread_kill(thread_id, signalnum)
Send the signal signalnum to the thread thread_id, another thread in the same process as the caller. The target thread can be executing any code (Python or not). However, if the target thread is executing the Python interpreter, the Python signal handlers will be executed by the main thread of the main interpreter. Therefore, the only point of sending a signal to a particular Python thread would be to force a running system call to fail with InterruptedError. Use threading.get_ident() or the ident attribute of threading.Thread objects to get a suitable value for thread_id. If signalnum is 0, then no signal is sent, but error checking is still performed; this can be used to check if the target thread is still running. Raises an auditing event signal.pthread_kill with arguments thread_id, signalnum. Availability: Unix. See the man page pthread_kill(3) for further information. See also os.kill(). New in version 3.3. | python.library.signal#signal.pthread_kill |
signal.pthread_sigmask(how, mask)
Fetch and/or change the signal mask of the calling thread. The signal mask is the set of signals whose delivery is currently blocked for the caller. Return the old signal mask as a set of signals. The behavior of the call is dependent on the value of how, as follows.
SIG_BLOCK: The set of blocked signals is the union of the current set and the mask argument.
SIG_UNBLOCK: The signals in mask are removed from the current set of blocked signals. It is permissible to attempt to unblock a signal which is not blocked.
SIG_SETMASK: The set of blocked signals is set to the mask argument. mask is a set of signal numbers (e.g. {signal.SIGINT, signal.SIGTERM}). Use valid_signals() for a full mask including all signals. For example, signal.pthread_sigmask(signal.SIG_BLOCK, []) reads the signal mask of the calling thread. SIGKILL and SIGSTOP cannot be blocked. Availability: Unix. See the man page sigprocmask(3) and pthread_sigmask(3) for further information. See also pause(), sigpending() and sigwait(). New in version 3.3. | python.library.signal#signal.pthread_sigmask |
signal.raise_signal(signum)
Sends a signal to the calling process. Returns nothing. New in version 3.8. | python.library.signal#signal.raise_signal |
signal.setitimer(which, seconds, interval=0.0)
Sets given interval timer (one of signal.ITIMER_REAL, signal.ITIMER_VIRTUAL or signal.ITIMER_PROF) specified by which to fire after seconds (float is accepted, different from alarm()) and after that every interval seconds (if interval is non-zero). The interval timer specified by which can be cleared by setting seconds to zero. When an interval timer fires, a signal is sent to the process. The signal sent is dependent on the timer being used; signal.ITIMER_REAL will deliver SIGALRM, signal.ITIMER_VIRTUAL sends SIGVTALRM, and signal.ITIMER_PROF will deliver SIGPROF. The old values are returned as a tuple: (delay, interval). Attempting to pass an invalid interval timer will cause an ItimerError. Availability: Unix. | python.library.signal#signal.setitimer |
signal.set_wakeup_fd(fd, *, warn_on_full_buffer=True)
Set the wakeup file descriptor to fd. When a signal is received, the signal number is written as a single byte into the fd. This can be used by a library to wakeup a poll or select call, allowing the signal to be fully processed. The old wakeup fd is returned (or -1 if file descriptor wakeup was not enabled). If fd is -1, file descriptor wakeup is disabled. If not -1, fd must be non-blocking. It is up to the library to remove any bytes from fd before calling poll or select again. When threads are enabled, this function can only be called from the main thread of the main interpreter; attempting to call it from other threads will cause a ValueError exception to be raised. There are two common ways to use this function. In both approaches, you use the fd to wake up when a signal arrives, but then they differ in how they determine which signal or signals have arrived. In the first approach, we read the data out of the fd’s buffer, and the byte values give you the signal numbers. This is simple, but in rare cases it can run into a problem: generally the fd will have a limited amount of buffer space, and if too many signals arrive too quickly, then the buffer may become full, and some signals may be lost. If you use this approach, then you should set warn_on_full_buffer=True, which will at least cause a warning to be printed to stderr when signals are lost. In the second approach, we use the wakeup fd only for wakeups, and ignore the actual byte values. In this case, all we care about is whether the fd’s buffer is empty or non-empty; a full buffer doesn’t indicate a problem at all. If you use this approach, then you should set warn_on_full_buffer=False, so that your users are not confused by spurious warning messages. Changed in version 3.5: On Windows, the function now also supports socket handles. Changed in version 3.7: Added warn_on_full_buffer parameter. | python.library.signal#signal.set_wakeup_fd |
signal.SIGABRT
Abort signal from abort(3). | python.library.signal#signal.SIGABRT |
signal.SIGALRM
Timer signal from alarm(2). Availability: Unix. | python.library.signal#signal.SIGALRM |
signal.SIGBREAK
Interrupt from keyboard (CTRL + BREAK). Availability: Windows. | python.library.signal#signal.SIGBREAK |
signal.SIGBUS
Bus error (bad memory access). Availability: Unix. | python.library.signal#signal.SIGBUS |
signal.SIGCHLD
Child process stopped or terminated. Availability: Unix. | python.library.signal#signal.SIGCHLD |
signal.SIGCLD
Alias to SIGCHLD. | python.library.signal#signal.SIGCLD |
signal.SIGCONT
Continue the process if it is currently stopped Availability: Unix. | python.library.signal#signal.SIGCONT |
signal.SIGFPE
Floating-point exception. For example, division by zero. See also ZeroDivisionError is raised when the second argument of a division or modulo operation is zero. | python.library.signal#signal.SIGFPE |
signal.SIGHUP
Hangup detected on controlling terminal or death of controlling process. Availability: Unix. | python.library.signal#signal.SIGHUP |
signal.SIGILL
Illegal instruction. | python.library.signal#signal.SIGILL |
signal.SIGINT
Interrupt from keyboard (CTRL + C). Default action is to raise KeyboardInterrupt. | python.library.signal#signal.SIGINT |
signal.siginterrupt(signalnum, flag)
Change system call restart behaviour: if flag is False, system calls will be restarted when interrupted by signal signalnum, otherwise system calls will be interrupted. Returns nothing. Availability: Unix. See the man page siginterrupt(3) for further information. Note that installing a signal handler with signal() will reset the restart behaviour to interruptible by implicitly calling siginterrupt() with a true flag value for the given signal. | python.library.signal#signal.siginterrupt |
signal.SIGKILL
Kill signal. It cannot be caught, blocked, or ignored. Availability: Unix. | python.library.signal#signal.SIGKILL |
signal.signal(signalnum, handler)
Set the handler for signal signalnum to the function handler. handler can be a callable Python object taking two arguments (see below), or one of the special values signal.SIG_IGN or signal.SIG_DFL. The previous signal handler will be returned (see the description of getsignal() above). (See the Unix man page signal(2) for further information.) When threads are enabled, this function can only be called from the main thread of the main interpreter; attempting to call it from other threads will cause a ValueError exception to be raised. The handler is called with two arguments: the signal number and the current stack frame (None or a frame object; for a description of frame objects, see the description in the type hierarchy or see the attribute descriptions in the inspect module). On Windows, signal() can only be called with SIGABRT, SIGFPE, SIGILL, SIGINT, SIGSEGV, SIGTERM, or SIGBREAK. A ValueError will be raised in any other case. Note that not all systems define the same set of signal names; an AttributeError will be raised if a signal name is not defined as SIG* module level constant. | python.library.signal#signal.signal |
signal.sigpending()
Examine the set of signals that are pending for delivery to the calling thread (i.e., the signals which have been raised while blocked). Return the set of the pending signals. Availability: Unix. See the man page sigpending(2) for further information. See also pause(), pthread_sigmask() and sigwait(). New in version 3.3. | python.library.signal#signal.sigpending |
signal.SIGPIPE
Broken pipe: write to pipe with no readers. Default action is to ignore the signal. Availability: Unix. | python.library.signal#signal.SIGPIPE |
signal.SIGSEGV
Segmentation fault: invalid memory reference. | python.library.signal#signal.SIGSEGV |
signal.SIGTERM
Termination signal. | python.library.signal#signal.SIGTERM |
signal.sigtimedwait(sigset, timeout)
Like sigwaitinfo(), but takes an additional timeout argument specifying a timeout. If timeout is specified as 0, a poll is performed. Returns None if a timeout occurs. Availability: Unix. See the man page sigtimedwait(2) for further information. See also pause(), sigwait() and sigwaitinfo(). New in version 3.3. Changed in version 3.5: The function is now retried with the recomputed timeout if interrupted by a signal not in sigset and the signal handler does not raise an exception (see PEP 475 for the rationale). | python.library.signal#signal.sigtimedwait |
signal.SIGUSR1
User-defined signal 1. Availability: Unix. | python.library.signal#signal.SIGUSR1 |
signal.SIGUSR2
User-defined signal 2. Availability: Unix. | python.library.signal#signal.SIGUSR2 |
signal.sigwait(sigset)
Suspend execution of the calling thread until the delivery of one of the signals specified in the signal set sigset. The function accepts the signal (removes it from the pending list of signals), and returns the signal number. Availability: Unix. See the man page sigwait(3) for further information. See also pause(), pthread_sigmask(), sigpending(), sigwaitinfo() and sigtimedwait(). New in version 3.3. | python.library.signal#signal.sigwait |
signal.sigwaitinfo(sigset)
Suspend execution of the calling thread until the delivery of one of the signals specified in the signal set sigset. The function accepts the signal and removes it from the pending list of signals. If one of the signals in sigset is already pending for the calling thread, the function will return immediately with information about that signal. The signal handler is not called for the delivered signal. The function raises an InterruptedError if it is interrupted by a signal that is not in sigset. The return value is an object representing the data contained in the siginfo_t structure, namely: si_signo, si_code, si_errno, si_pid, si_uid, si_status, si_band. Availability: Unix. See the man page sigwaitinfo(2) for further information. See also pause(), sigwait() and sigtimedwait(). New in version 3.3. Changed in version 3.5: The function is now retried if interrupted by a signal not in sigset and the signal handler does not raise an exception (see PEP 475 for the rationale). | python.library.signal#signal.sigwaitinfo |
signal.SIGWINCH
Window resize signal. Availability: Unix. | python.library.signal#signal.SIGWINCH |
signal.SIG_BLOCK
A possible value for the how parameter to pthread_sigmask() indicating that signals are to be blocked. New in version 3.3. | python.library.signal#signal.SIG_BLOCK |
signal.SIG_DFL
This is one of two standard signal handling options; it will simply perform the default function for the signal. For example, on most systems the default action for SIGQUIT is to dump core and exit, while the default action for SIGCHLD is to simply ignore it. | python.library.signal#signal.SIG_DFL |
signal.SIG_IGN
This is another standard signal handler, which will simply ignore the given signal. | python.library.signal#signal.SIG_IGN |
signal.SIG_SETMASK
A possible value for the how parameter to pthread_sigmask() indicating that the signal mask is to be replaced. New in version 3.3. | python.library.signal#signal.SIG_SETMASK |
signal.SIG_UNBLOCK
A possible value for the how parameter to pthread_sigmask() indicating that signals are to be unblocked. New in version 3.3. | python.library.signal#signal.SIG_UNBLOCK |
signal.strsignal(signalnum)
Return the system description of the signal signalnum, such as “Interrupt”, “Segmentation fault”, etc. Returns None if the signal is not recognized. New in version 3.8. | python.library.signal#signal.strsignal |
signal.valid_signals()
Return the set of valid signal numbers on this platform. This can be less than range(1, NSIG) if some signals are reserved by the system for internal use. New in version 3.8. | python.library.signal#signal.valid_signals |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.