This module provides mechanisms to use signal handlers in Python.
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.
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:
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.
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:
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.
This is another standard signal handler, which will simply ignore the given signal.
Abort signal from abort(3).
Timer signal from alarm(2).
Availability: Unix.
Interrupt from keyboard (CTRL + BREAK).
Availability: Windows.
Bus error (bad memory access).
Availability: Unix.
Child process stopped or terminated.
Availability: Unix.
Alias to SIGCHLD.
Continue the process if it is currently stopped
Availability: Unix.
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.
Hangup detected on controlling terminal or death of controlling process.
Availability: Unix.
Illegal instruction.
Interrupt from keyboard (CTRL + C).
Default action is to raise KeyboardInterrupt.
Kill signal.
It cannot be caught, blocked, or ignored.
Availability: Unix.
Broken pipe: write to pipe with no readers.
Default action is to ignore the signal.
Availability: Unix.
Segmentation fault: invalid memory reference.
Termination signal.
User-defined signal 1.
Availability: Unix.
User-defined signal 2.
Availability: Unix.
Window resize signal.
Availability: Unix.
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.
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.
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.
One more than the number of the highest signal number.
Decrements interval timer in real time, and delivers SIGALRM upon expiration.
Decrements interval timer only when the process is executing, and delivers SIGVTALRM upon expiration.
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.
A possible value for the how parameter to pthread_sigmask() indicating that signals are to be blocked.
New in version 3.3.
A possible value for the how parameter to pthread_sigmask() indicating that signals are to be unblocked.
New in version 3.3.
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:
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:
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.
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.
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.
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.
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().
Sends a signal to the calling process. Returns nothing.
New in version 3.8.
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.
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.
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.
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.
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.
Returns current value of a given interval timer specified by which.
Availability: Unix.
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.
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.
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.
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.
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.
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).
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).
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.
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:
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.


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.


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.


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.


Returns current value of a given interval timer specified by which.
Availability: Unix.


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.


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.


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.


Decrements interval timer in real time, and delivers SIGALRM upon expiration.


Decrements interval timer only when the process is executing, and delivers SIGVTALRM upon expiration.


One more than the number of the highest signal number.


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().


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.


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.


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.
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.


Sends a signal to the calling process. Returns nothing.
New in version 3.8.


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.


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.


Timer signal from alarm(2).
Availability: Unix.


Interrupt from keyboard (CTRL + BREAK).
Availability: Windows.


Bus error (bad memory access).
Availability: Unix.


Child process stopped or terminated.
Availability: Unix.


Continue the process if it is currently stopped
Availability: Unix.


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.


Hangup detected on controlling terminal or death of controlling process.
Availability: Unix.


Interrupt from keyboard (CTRL + C).
Default action is to raise KeyboardInterrupt.


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.


Kill signal.
It cannot be caught, blocked, or ignored.
Availability: Unix.


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.


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.


Broken pipe: write to pipe with no readers.
Default action is to ignore the signal.
Availability: Unix.


Segmentation fault: invalid memory reference.


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).


User-defined signal 1.
Availability: Unix.


User-defined signal 2.
Availability: Unix.


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.


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).


Window resize signal.
Availability: Unix.


A possible value for the how parameter to pthread_sigmask() indicating that signals are to be blocked.
New in version 3.3.


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.


This is another standard signal handler, which will simply ignore the given signal.


A possible value for the how parameter to pthread_sigmask() indicating that the signal mask is to be replaced.
New in version 3.3.


A possible value for the how parameter to pthread_sigmask() indicating that signals are to be unblocked.
New in version 3.3.


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.


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.


Source code: Lib/site.py
This module is automatically imported during initialization. The automatic import can be suppressed using the interpreter’s -S option.
Importing this module will append site-specific paths to the module search path and add a few builtins, unless -S was used. In that case, this module can be safely imported with no automatic modifications to the module search path or additions to the builtins. To explicitly trigger the usual site-specific additions, call the site.main() function.
Changed in version 3.3: Importing the module used to trigger paths manipulation even when using -S.
It starts by constructing up to four directories from a head and a tail part. For the head part, it uses sys.prefix and sys.exec_prefix; empty heads are skipped. For the tail part, it uses the empty string and then lib/site-packages (on Windows) or lib/pythonX.Y/site-packages (on Unix and Macintosh). For each of the distinct head-tail combinations, it sees if it refers to an existing directory, and if so, adds it to sys.path and also inspects the newly added path for configuration files.
Changed in version 3.5: Support for the “site-python” directory has been removed.
If a file named “pyvenv.cfg” exists one directory above sys.executable, sys.prefix and sys.exec_prefix are set to that directory and it is also checked for site-packages (sys.base_prefix and sys.base_exec_prefix will always be the “real” prefixes of the Python installation). If “pyvenv.cfg” (a bootstrap configuration file) contains the key “include-system-site-packages” set to anything other than “true” (case-insensitive), the system-level prefixes will not be searched for site-packages; otherwise they will.
A path configuration file is a file whose name has the form name.pth and exists in one of the four directories mentioned above; its contents are additional items (one per line) to be added to sys.path. Non-existing items are never added to sys.path, and no check is made that the item refers to a directory rather than a file. No item is added to sys.path more than once. Blank lines and lines beginning with # are skipped. Lines starting with import (followed by space or tab) are executed.
Note
An executable line in a .pth file is run at every Python startup, regardless of whether a particular module is actually going to be used. Its impact should thus be kept to a minimum. The primary intended purpose of executable lines is to make the corresponding module(s) importable (load 3rd-party import hooks, adjust PATH etc). Any other initialization is supposed to be done upon a module’s actual import, if and when it happens. Limiting a code chunk to a single line is a deliberate measure to discourage putting anything more complex here.
For example, suppose sys.prefix and sys.exec_prefix are set to /usr/local. The Python X.Y library is then installed in /usr/local/lib/pythonX.Y. Suppose this has a subdirectory /usr/local/lib/pythonX.Y/site-packages with three subsubdirectories, foo, bar and spam, and two path configuration files, foo.pth and bar.pth. Assume foo.pth contains the following:
and bar.pth contains:
Then the following version-specific directories are added to sys.path, in this order:
Note that bletch is omitted because it doesn’t exist; the bar directory precedes the foo directory because bar.pth comes alphabetically before foo.pth; and spam is omitted because it is not mentioned in either path configuration file.
After these path manipulations, an attempt is made to import a module named sitecustomize, which can perform arbitrary site-specific customizations. It is typically created by a system administrator in the site-packages directory. If this import fails with an ImportError or its subclass exception, and the exception’s name attribute equals to 'sitecustomize', it is silently ignored. If Python is started without output streams available, as with pythonw.exe on Windows (which is used by default to start IDLE), attempted output from sitecustomize is ignored. Any other exception causes a silent and perhaps mysterious failure of the process.
After this, an attempt is made to import a module named usercustomize, which can perform arbitrary user-specific customizations, if ENABLE_USER_SITE is true. This file is intended to be created in the user site-packages directory (see below), which is part of sys.path unless disabled by -s. If this import fails with an ImportError or its subclass exception, and the exception’s name attribute equals to 'usercustomize', it is silently ignored.
Note that for some non-Unix systems, sys.prefix and sys.exec_prefix are empty, and the path manipulations are skipped; however the import of sitecustomize and usercustomize is still attempted.
On systems that support readline, this module will also import and configure the rlcompleter module, if Python is started in interactive mode and without the -S option. The default behavior is enable tab-completion and to use ~/.python_history as the history save file. To disable it, delete (or override) the sys.__interactivehook__ attribute in your sitecustomize or usercustomize module or your PYTHONSTARTUP file.
Changed in version 3.4: Activation of rlcompleter and history was made automatic.
A list of prefixes for site-packages directories.
Flag showing the status of the user site-packages directory. True means that it is enabled and was added to sys.path. False means that it was disabled by user request (with -s or PYTHONNOUSERSITE). None means it was disabled for security reasons (mismatch between user or group id and effective id) or by an administrator.
Path to the user site-packages for the running Python. Can be None if getusersitepackages() hasn’t been called yet. Default value is ~/.local/lib/pythonX.Y/site-packages for UNIX and non-framework Mac OS X builds, ~/Library/Python/X.Y/lib/python/site-packages for Mac framework builds, and %APPDATA%\Python\PythonXY\site-packages on Windows. This directory is a site directory, which means that .pth files in it will be processed.
Path to the base directory for the user site-packages. Can be None if getuserbase() hasn’t been called yet. Default value is ~/.local for UNIX and Mac OS X non-framework builds, ~/Library/Python/X.Y for Mac framework builds, and %APPDATA%\Python for Windows. This value is used by Distutils to compute the installation directories for scripts, data files, Python modules, etc. for the user installation scheme. See also PYTHONUSERBASE.
Adds all the standard site-specific directories to the module search path. This function is called automatically when this module is imported, unless the Python interpreter was started with the -S flag.
Changed in version 3.3: This function used to be called unconditionally.
Add a directory to sys.path and process its .pth files. Typically used in sitecustomize or usercustomize (see above).
Return a list containing all global site-packages directories.
New in version 3.2.
Return the path of the user base directory, USER_BASE. If it is not initialized yet, this function will also set it, respecting PYTHONUSERBASE.
New in version 3.2.
Return the path of the user-specific site-packages directory, USER_SITE. If it is not initialized yet, this function will also set it, respecting USER_BASE. To determine if the user-specific site-packages was added to sys.path ENABLE_USER_SITE should be used.
New in version 3.2.
The site module also provides a way to get the user directories from the command line:
If it is called without arguments, it will print the contents of sys.path on the standard output, followed by the value of USER_BASE and whether the directory exists, then the same thing for USER_SITE, and finally the value of ENABLE_USER_SITE.
Print the path to the user base directory.
Print the path to the user site-packages directory.
If both options are given, user base and user site will be printed (always in this order), separated by os.pathsep.
If any option is given, the script will exit with one of these values: 0 if the user site-packages directory is enabled, 1 if it was disabled by the user, 2 if it is disabled for security reasons or by an administrator, and a value greater than 2 if there is an error.
See also
PEP 370 – Per user site-packages directory


Add a directory to sys.path and process its .pth files. Typically used in sitecustomize or usercustomize (see above).


Flag showing the status of the user site-packages directory. True means that it is enabled and was added to sys.path. False means that it was disabled by user request (with -s or PYTHONNOUSERSITE). None means it was disabled for security reasons (mismatch between user or group id and effective id) or by an administrator.


Return a list containing all global site-packages directories.
New in version 3.2.


Return the path of the user base directory, USER_BASE. If it is not initialized yet, this function will also set it, respecting PYTHONUSERBASE.
New in version 3.2.


Return the path of the user-specific site-packages directory, USER_SITE. If it is not initialized yet, this function will also set it, respecting USER_BASE. To determine if the user-specific site-packages was added to sys.path ENABLE_USER_SITE should be used.
New in version 3.2.


Adds all the standard site-specific directories to the module search path. This function is called automatically when this module is imported, unless the Python interpreter was started with the -S flag.
Changed in version 3.3: This function used to be called unconditionally.


A list of prefixes for site-packages directories.


Path to the base directory for the user site-packages. Can be None if getuserbase() hasn’t been called yet. Default value is ~/.local for UNIX and Mac OS X non-framework builds, ~/Library/Python/X.Y for Mac framework builds, and %APPDATA%\Python for Windows. This value is used by Distutils to compute the installation directories for scripts, data files, Python modules, etc. for the user installation scheme. See also PYTHONUSERBASE.


Path to the user site-packages for the running Python. Can be None if getusersitepackages() hasn’t been called yet. Default value is ~/.local/lib/pythonX.Y/site-packages for UNIX and non-framework Mac OS X builds, ~/Library/Python/X.Y/lib/python/site-packages for Mac framework builds, and %APPDATA%\Python\PythonXY\site-packages on Windows. This directory is a site directory, which means that .pth files in it will be processed.


Return a slice object representing the set of indices specified by range(start, stop, step). The start and step arguments default to None. Slice objects have read-only data attributes start, stop and step which merely return the argument values (or their default). They have no other explicit functionality; however they are used by Numerical Python and other third party extensions. Slice objects are also generated when extended indexing syntax is used. For example: a[start:stop:step] or a[start:stop, i]. See itertools.islice() for an alternate version that returns an iterator.


Source code: Lib/smtpd.py
This module offers several classes to implement SMTP (email) servers.
See also
The aiosmtpd package is a recommended replacement for this module. It is based on asyncio and provides a more straightforward API. smtpd should be considered deprecated.
Several server implementations are present; one is a generic do-nothing implementation, which can be overridden, while the other two offer specific mail-sending strategies.
Additionally the SMTPChannel may be extended to implement very specific interaction behaviour with SMTP clients.
The code supports RFC 5321, plus the RFC 1870 SIZE and RFC 6531 SMTPUTF8 extensions.
Create a new SMTPServer object, which binds to local address localaddr. It will treat remoteaddr as an upstream SMTP relayer. Both localaddr and remoteaddr should be a (host, port) tuple. The object inherits from asyncore.dispatcher, and so will insert itself into asyncore’s event loop on instantiation.
data_size_limit specifies the maximum number of bytes that will be accepted in a DATA command. A value of None or 0 means no limit.
map is the socket map to use for connections (an initially empty dictionary is a suitable value). If not specified the asyncore global socket map is used.
enable_SMTPUTF8 determines whether the SMTPUTF8 extension (as defined in RFC 6531) should be enabled. The default is False. When True, SMTPUTF8 is accepted as a parameter to the MAIL command and when present is passed to process_message() in the kwargs['mail_options'] list. decode_data and enable_SMTPUTF8 cannot be set to True at the same time.
decode_data specifies whether the data portion of the SMTP transaction should be decoded using UTF-8. When decode_data is False (the default), the server advertises the 8BITMIME extension (RFC 6152), accepts the BODY=8BITMIME parameter to the MAIL command, and when present passes it to process_message() in the kwargs['mail_options'] list. decode_data and enable_SMTPUTF8 cannot be set to True at the same time.
Raise a NotImplementedError exception. Override this in subclasses to do something useful with this message. Whatever was passed in the constructor as remoteaddr will be available as the _remoteaddr attribute. peer is the remote host’s address, mailfrom is the envelope originator, rcpttos are the envelope recipients and data is a string containing the contents of the e-mail (which should be in RFC 5321 format).
If the decode_data constructor keyword is set to True, the data argument will be a unicode string. If it is set to False, it will be a bytes object.
kwargs is a dictionary containing additional information. It is empty if decode_data=True was given as an init argument, otherwise it contains the following keys:
a list of all received parameters to the MAIL command (the elements are uppercase strings; example: ['BODY=8BITMIME', 'SMTPUTF8']).
same as mail_options but for the RCPT command. Currently no RCPT TO options are supported, so for now this will always be an empty list.
Implementations of process_message should use the **kwargs signature to accept arbitrary keyword arguments, since future feature enhancements may add keys to the kwargs dictionary.
Return None to request a normal 250 Ok response; otherwise return the desired response string in RFC 5321 format.
Override this in subclasses to use a custom SMTPChannel for managing SMTP clients.
New in version 3.4: The map constructor argument.
Changed in version 3.5: localaddr and remoteaddr may now contain IPv6 addresses.
New in version 3.5: The decode_data and enable_SMTPUTF8 constructor parameters, and the kwargs parameter to process_message() when decode_data is False.
Changed in version 3.6: decode_data is now False by default.
Create a new debugging server. Arguments are as per SMTPServer. Messages will be discarded, and printed on stdout.
Create a new pure proxy server. Arguments are as per SMTPServer. Everything will be relayed to remoteaddr. Note that running this has a good chance to make you into an open relay, so please be careful.
Deprecated since version 3.9, will be removed in version 3.11: MailmanProxy is deprecated, it depends on a Mailman module which no longer exists and therefore is already broken.
Create a new pure proxy server. Arguments are as per SMTPServer. Everything will be relayed to remoteaddr, unless local mailman configurations knows about an address, in which case it will be handled via mailman. Note that running this has a good chance to make you into an open relay, so please be careful.
Create a new SMTPChannel object which manages the communication between the server and a single SMTP client.
conn and addr are as per the instance variables described below.
data_size_limit specifies the maximum number of bytes that will be accepted in a DATA command. A value of None or 0 means no limit.
enable_SMTPUTF8 determines whether the SMTPUTF8 extension (as defined in RFC 6531) should be enabled. The default is False. decode_data and enable_SMTPUTF8 cannot be set to True at the same time.
A dictionary can be specified in map to avoid using a global socket map.
decode_data specifies whether the data portion of the SMTP transaction should be decoded using UTF-8. The default is False. decode_data and enable_SMTPUTF8 cannot be set to True at the same time.
To use a custom SMTPChannel implementation you need to override the SMTPServer.channel_class of your SMTPServer.
Changed in version 3.5: The decode_data and enable_SMTPUTF8 parameters were added.
Changed in version 3.6: decode_data is now False by default.
The SMTPChannel has the following instance variables:
Holds the SMTPServer that spawned this channel.
Holds the socket object connecting to the client.
Holds the address of the client, the second value returned by socket.accept
Holds a list of the line strings (decoded using UTF-8) received from the client. The lines have their "\r\n" line ending translated to "\n".
Holds the current state of the channel. This will be either COMMAND initially and then DATA after the client sends a “DATA” line.
Holds a string containing the greeting sent by the client in its “HELO”.
Holds a string containing the address identified in the “MAIL FROM:” line from the client.
Holds a list of strings containing the addresses identified in the “RCPT TO:” lines from the client.
Holds a string containing all of the data sent by the client during the DATA state, up to but not including the terminating "\r\n.\r\n".
Holds the fully-qualified domain name of the server as returned by socket.getfqdn().
Holds the name of the client peer as returned by conn.getpeername() where conn is conn.
The SMTPChannel operates by invoking methods named smtp_<command> upon reception of a command line from the client. Built into the base SMTPChannel class are methods for handling the following commands (and responding to them appropriately):
Command
Action taken
HELO
Accepts the greeting from the client and stores it in seen_greeting. Sets server to base command mode.
EHLO
Accepts the greeting from the client and stores it in seen_greeting. Sets server to extended command mode.
NOOP
Takes no action.
QUIT
Closes the connection cleanly.
MAIL
Accepts the “MAIL FROM:” syntax and stores the supplied address as mailfrom. In extended command mode, accepts the RFC 1870 SIZE attribute and responds appropriately based on the value of data_size_limit.
RCPT
Accepts the “RCPT TO:” syntax and stores the supplied addresses in the rcpttos list.
RSET
Resets the mailfrom, rcpttos, and received_data, but not the greeting.
DATA
Sets the internal state to DATA and stores remaining lines from the client in received_data until the terminator "\r\n.\r\n" is received.
HELP
Returns minimal information on command syntax
VRFY
Returns code 252 (the server doesn’t know if the address is valid)
EXPN
Reports that the command is not implemented.


Create a new debugging server. Arguments are as per SMTPServer. Messages will be discarded, and printed on stdout.


Deprecated since version 3.9, will be removed in version 3.11: MailmanProxy is deprecated, it depends on a Mailman module which no longer exists and therefore is already broken.
Create a new pure proxy server. Arguments are as per SMTPServer. Everything will be relayed to remoteaddr, unless local mailman configurations knows about an address, in which case it will be handled via mailman. Note that running this has a good chance to make you into an open relay, so please be careful.


Create a new pure proxy server. Arguments are as per SMTPServer. Everything will be relayed to remoteaddr. Note that running this has a good chance to make you into an open relay, so please be careful.


Create a new SMTPChannel object which manages the communication between the server and a single SMTP client.
conn and addr are as per the instance variables described below.
data_size_limit specifies the maximum number of bytes that will be accepted in a DATA command. A value of None or 0 means no limit.
enable_SMTPUTF8 determines whether the SMTPUTF8 extension (as defined in RFC 6531) should be enabled. The default is False. decode_data and enable_SMTPUTF8 cannot be set to True at the same time.
A dictionary can be specified in map to avoid using a global socket map.
decode_data specifies whether the data portion of the SMTP transaction should be decoded using UTF-8. The default is False. decode_data and enable_SMTPUTF8 cannot be set to True at the same time.
To use a custom SMTPChannel implementation you need to override the SMTPServer.channel_class of your SMTPServer.
Changed in version 3.5: The decode_data and enable_SMTPUTF8 parameters were added.
Changed in version 3.6: decode_data is now False by default.
The SMTPChannel has the following instance variables:
Holds the SMTPServer that spawned this channel.
Holds the socket object connecting to the client.
Holds the address of the client, the second value returned by socket.accept
Holds a list of the line strings (decoded using UTF-8) received from the client. The lines have their "\r\n" line ending translated to "\n".
Holds the current state of the channel. This will be either COMMAND initially and then DATA after the client sends a “DATA” line.
Holds a string containing the greeting sent by the client in its “HELO”.
Holds a string containing the address identified in the “MAIL FROM:” line from the client.
Holds a list of strings containing the addresses identified in the “RCPT TO:” lines from the client.
Holds a string containing all of the data sent by the client during the DATA state, up to but not including the terminating "\r\n.\r\n".
Holds the fully-qualified domain name of the server as returned by socket.getfqdn().
Holds the name of the client peer as returned by conn.getpeername() where conn is conn.
The SMTPChannel operates by invoking methods named smtp_<command> upon reception of a command line from the client. Built into the base SMTPChannel class are methods for handling the following commands (and responding to them appropriately):
Command
Action taken
HELO
Accepts the greeting from the client and stores it in seen_greeting. Sets server to base command mode.
EHLO
Accepts the greeting from the client and stores it in seen_greeting. Sets server to extended command mode.
NOOP
Takes no action.
QUIT
Closes the connection cleanly.
MAIL
Accepts the “MAIL FROM:” syntax and stores the supplied address as mailfrom. In extended command mode, accepts the RFC 1870 SIZE attribute and responds appropriately based on the value of data_size_limit.
RCPT
Accepts the “RCPT TO:” syntax and stores the supplied addresses in the rcpttos list.
RSET
Resets the mailfrom, rcpttos, and received_data, but not the greeting.
DATA
Sets the internal state to DATA and stores remaining lines from the client in received_data until the terminator "\r\n.\r\n" is received.
HELP
Returns minimal information on command syntax
VRFY
Returns code 252 (the server doesn’t know if the address is valid)
EXPN
Reports that the command is not implemented.


Holds the address of the client, the second value returned by socket.accept


Holds the socket object connecting to the client.


Holds the fully-qualified domain name of the server as returned by socket.getfqdn().


Holds a string containing the address identified in the “MAIL FROM:” line from the client.


Holds the name of the client peer as returned by conn.getpeername() where conn is conn.


Holds a list of strings containing the addresses identified in the “RCPT TO:” lines from the client.


Holds a string containing all of the data sent by the client during the DATA state, up to but not including the terminating "\r\n.\r\n".


Holds a list of the line strings (decoded using UTF-8) received from the client. The lines have their "\r\n" line ending translated to "\n".


Holds a string containing the greeting sent by the client in its “HELO”.


Holds the SMTPServer that spawned this channel.


Holds the current state of the channel. This will be either COMMAND initially and then DATA after the client sends a “DATA” line.


Create a new SMTPServer object, which binds to local address localaddr. It will treat remoteaddr as an upstream SMTP relayer. Both localaddr and remoteaddr should be a (host, port) tuple. The object inherits from asyncore.dispatcher, and so will insert itself into asyncore’s event loop on instantiation.
data_size_limit specifies the maximum number of bytes that will be accepted in a DATA command. A value of None or 0 means no limit.
map is the socket map to use for connections (an initially empty dictionary is a suitable value). If not specified the asyncore global socket map is used.
enable_SMTPUTF8 determines whether the SMTPUTF8 extension (as defined in RFC 6531) should be enabled. The default is False. When True, SMTPUTF8 is accepted as a parameter to the MAIL command and when present is passed to process_message() in the kwargs['mail_options'] list. decode_data and enable_SMTPUTF8 cannot be set to True at the same time.
decode_data specifies whether the data portion of the SMTP transaction should be decoded using UTF-8. When decode_data is False (the default), the server advertises the 8BITMIME extension (RFC 6152), accepts the BODY=8BITMIME parameter to the MAIL command, and when present passes it to process_message() in the kwargs['mail_options'] list. decode_data and enable_SMTPUTF8 cannot be set to True at the same time.
Raise a NotImplementedError exception. Override this in subclasses to do something useful with this message. Whatever was passed in the constructor as remoteaddr will be available as the _remoteaddr attribute. peer is the remote host’s address, mailfrom is the envelope originator, rcpttos are the envelope recipients and data is a string containing the contents of the e-mail (which should be in RFC 5321 format).
If the decode_data constructor keyword is set to True, the data argument will be a unicode string. If it is set to False, it will be a bytes object.
kwargs is a dictionary containing additional information. It is empty if decode_data=True was given as an init argument, otherwise it contains the following keys:
a list of all received parameters to the MAIL command (the elements are uppercase strings; example: ['BODY=8BITMIME', 'SMTPUTF8']).
same as mail_options but for the RCPT command. Currently no RCPT TO options are supported, so for now this will always be an empty list.
Implementations of process_message should use the **kwargs signature to accept arbitrary keyword arguments, since future feature enhancements may add keys to the kwargs dictionary.
Return None to request a normal 250 Ok response; otherwise return the desired response string in RFC 5321 format.
Override this in subclasses to use a custom SMTPChannel for managing SMTP clients.
New in version 3.4: The map constructor argument.
Changed in version 3.5: localaddr and remoteaddr may now contain IPv6 addresses.
New in version 3.5: The decode_data and enable_SMTPUTF8 constructor parameters, and the kwargs parameter to process_message() when decode_data is False.
Changed in version 3.6: decode_data is now False by default.


Override this in subclasses to use a custom SMTPChannel for managing SMTP clients.


Raise a NotImplementedError exception. Override this in subclasses to do something useful with this message. Whatever was passed in the constructor as remoteaddr will be available as the _remoteaddr attribute. peer is the remote host’s address, mailfrom is the envelope originator, rcpttos are the envelope recipients and data is a string containing the contents of the e-mail (which should be in RFC 5321 format).
If the decode_data constructor keyword is set to True, the data argument will be a unicode string. If it is set to False, it will be a bytes object.
kwargs is a dictionary containing additional information. It is empty if decode_data=True was given as an init argument, otherwise it contains the following keys:
a list of all received parameters to the MAIL command (the elements are uppercase strings; example: ['BODY=8BITMIME', 'SMTPUTF8']).
same as mail_options but for the RCPT command. Currently no RCPT TO options are supported, so for now this will always be an empty list.
Implementations of process_message should use the **kwargs signature to accept arbitrary keyword arguments, since future feature enhancements may add keys to the kwargs dictionary.
Return None to request a normal 250 Ok response; otherwise return the desired response string in RFC 5321 format.


Source code: Lib/smtplib.py
The smtplib module defines an SMTP client session object that can be used to send mail to any Internet machine with an SMTP or ESMTP listener daemon. For details of SMTP and ESMTP operation, consult RFC 821 (Simple Mail Transfer Protocol) and RFC 1869 (SMTP Service Extensions).
An SMTP instance encapsulates an SMTP connection. It has methods that support a full repertoire of SMTP and ESMTP operations. If the optional host and port parameters are given, the SMTP connect() method is called with those parameters during initialization. If specified, local_hostname is used as the FQDN of the local host in the HELO/EHLO command. Otherwise, the local hostname is found using socket.getfqdn(). If the connect() call returns anything other than a success code, an SMTPConnectError is raised. The optional timeout parameter specifies a timeout in seconds for blocking operations like the connection attempt (if not specified, the global default timeout setting will be used). If the timeout expires, socket.timeout is raised. The optional source_address parameter allows binding to some specific source address in a machine with multiple network interfaces, and/or to some specific source TCP port. It takes a 2-tuple (host, port), for the socket to bind to as its source address before connecting. If omitted (or if host or port are '' and/or 0 respectively) the OS default behavior will be used.
For normal use, you should only require the initialization/connect, sendmail(), and SMTP.quit() methods. An example is included below.
The SMTP class supports the with statement. When used like this, the SMTP QUIT command is issued automatically when the with statement exits. E.g.:
All commands will raise an auditing event smtplib.SMTP.send with arguments self and data, where data is the bytes about to be sent to the remote host.
Changed in version 3.3: Support for the with statement was added.
Changed in version 3.3: source_address argument was added.
New in version 3.5: The SMTPUTF8 extension (RFC 6531) is now supported.
Changed in version 3.9: If the timeout parameter is set to be zero, it will raise a ValueError to prevent the creation of a non-blocking socket
An SMTP_SSL instance behaves exactly the same as instances of SMTP. SMTP_SSL should be used for situations where SSL is required from the beginning of the connection and using starttls() is not appropriate. If host is not specified, the local host is used. If port is zero, the standard SMTP-over-SSL port (465) is used. The optional arguments local_hostname, timeout and source_address have the same meaning as they do in the SMTP class. context, also optional, can contain a SSLContext and allows configuring various aspects of the secure connection. Please read Security considerations for best practices.
keyfile and certfile are a legacy alternative to context, and can point to a PEM formatted private key and certificate chain file for the SSL connection.
Changed in version 3.3: context was added.
Changed in version 3.3: source_address argument was added.
Changed in version 3.4: The class now supports hostname check with ssl.SSLContext.check_hostname and Server Name Indication (see ssl.HAS_SNI).
Deprecated since version 3.6: keyfile and certfile are deprecated in favor of context. Please use ssl.SSLContext.load_cert_chain() instead, or let ssl.create_default_context() select the system’s trusted CA certificates for you.
Changed in version 3.9: If the timeout parameter is set to be zero, it will raise a ValueError to prevent the creation of a non-blocking socket
The LMTP protocol, which is very similar to ESMTP, is heavily based on the standard SMTP client. It’s common to use Unix sockets for LMTP, so our connect() method must support that as well as a regular host:port server. The optional arguments local_hostname and source_address have the same meaning as they do in the SMTP class. To specify a Unix socket, you must use an absolute path for host, starting with a ‘/’.
Authentication is supported, using the regular SMTP mechanism. When using a Unix socket, LMTP generally don’t support or require any authentication, but your mileage might vary.
Changed in version 3.9: The optional timeout parameter was added.
A nice selection of exceptions is defined as well:
Subclass of OSError that is the base exception class for all the other exceptions provided by this module.
Changed in version 3.4: SMTPException became subclass of OSError
This exception is raised when the server unexpectedly disconnects, or when an attempt is made to use the SMTP instance before connecting it to a server.
Base class for all exceptions that include an SMTP error code. These exceptions are generated in some instances when the SMTP server returns an error code. The error code is stored in the smtp_code attribute of the error, and the smtp_error attribute is set to the error message.
Sender address refused. In addition to the attributes set by on all SMTPResponseException exceptions, this sets ‘sender’ to the string that the SMTP server refused.
All recipient addresses refused. The errors for each recipient are accessible through the attribute recipients, which is a dictionary of exactly the same sort as SMTP.sendmail() returns.
The SMTP server refused to accept the message data.
Error occurred during establishment of a connection with the server.
The server refused our HELO message.
The command or option attempted is not supported by the server.
New in version 3.5.
SMTP authentication went wrong. Most probably the server didn’t accept the username/password combination provided.
See also
Protocol definition for SMTP. This document covers the model, operating procedure, and protocol details for SMTP.
Definition of the ESMTP extensions for SMTP. This describes a framework for extending SMTP with new commands, supporting dynamic discovery of the commands provided by the server, and defines a few additional commands.
An SMTP instance has the following methods:
Set the debug output level. A value of 1 or True for level results in debug messages for connection and for all messages sent to and received from the server. A value of 2 for level results in these messages being timestamped.
Changed in version 3.5: Added debuglevel 2.
Send a command cmd to the server. The optional argument args is simply concatenated to the command, separated by a space.
This returns a 2-tuple composed of a numeric response code and the actual response line (multiline responses are joined into one long line.)
In normal operation it should not be necessary to call this method explicitly. It is used to implement other methods and may be useful for testing private extensions.
If the connection to the server is lost while waiting for the reply, SMTPServerDisconnected will be raised.
Connect to a host on a given port. The defaults are to connect to the local host at the standard SMTP port (25). If the hostname ends with a colon (':') followed by a number, that suffix will be stripped off and the number interpreted as the port number to use. This method is automatically invoked by the constructor if a host is specified during instantiation. Returns a 2-tuple of the response code and message sent by the server in its connection response.
Raises an auditing event smtplib.connect with arguments self, host, port.
Identify yourself to the SMTP server using HELO. The hostname argument defaults to the fully qualified domain name of the local host. The message returned by the server is stored as the helo_resp attribute of the object.
In normal operation it should not be necessary to call this method explicitly. It will be implicitly called by the sendmail() when necessary.
Identify yourself to an ESMTP server using EHLO. The hostname argument defaults to the fully qualified domain name of the local host. Examine the response for ESMTP option and store them for use by has_extn(). Also sets several informational attributes: the message returned by the server is stored as the ehlo_resp attribute, does_esmtp is set to true or false depending on whether the server supports ESMTP, and esmtp_features will be a dictionary containing the names of the SMTP service extensions this server supports, and their parameters (if any).
Unless you wish to use has_extn() before sending mail, it should not be necessary to call this method explicitly. It will be implicitly called by sendmail() when necessary.
This method calls ehlo() and/or helo() if there has been no previous EHLO or HELO command this session. It tries ESMTP EHLO first.
The server didn’t reply properly to the HELO greeting.
Return True if name is in the set of SMTP service extensions returned by the server, False otherwise. Case is ignored.
Check the validity of an address on this server using SMTP VRFY. Returns a tuple consisting of code 250 and a full RFC 822 address (including human name) if the user address is valid. Otherwise returns an SMTP error code of 400 or greater and an error string.
Note
Many sites disable SMTP VRFY in order to foil spammers.
Log in on an SMTP server that requires authentication. The arguments are the username and the password to authenticate with. If there has been no previous EHLO or HELO command this session, this method tries ESMTP EHLO first. This method will return normally if the authentication was successful, or may raise the following exceptions:
The server didn’t reply properly to the HELO greeting.
The server didn’t accept the username/password combination.
The AUTH command is not supported by the server.
No suitable authentication method was found.
Each of the authentication methods supported by smtplib are tried in turn if they are advertised as supported by the server. See auth() for a list of supported authentication methods. initial_response_ok is passed through to auth().
Optional keyword argument initial_response_ok specifies whether, for authentication methods that support it, an “initial response” as specified in RFC 4954 can be sent along with the AUTH command, rather than requiring a challenge/response.
Changed in version 3.5: SMTPNotSupportedError may be raised, and the initial_response_ok parameter was added.
Issue an SMTP AUTH command for the specified authentication mechanism, and handle the challenge response via authobject.
mechanism specifies which authentication mechanism is to be used as argument to the AUTH command; the valid values are those listed in the auth element of esmtp_features.
authobject must be a callable object taking an optional single argument:
data = authobject(challenge=None)
If optional keyword argument initial_response_ok is true, authobject() will be called first with no argument. It can return the RFC 4954 “initial response” ASCII str which will be encoded and sent with the AUTH command as below. If the authobject() does not support an initial response (e.g. because it requires a challenge), it should return None when called with challenge=None. If initial_response_ok is false, then authobject() will not be called first with None.
If the initial response check returns None, or if initial_response_ok is false, authobject() will be called to process the server’s challenge response; the challenge argument it is passed will be a bytes. It should return ASCII str data that will be base64 encoded and sent to the server.
The SMTP class provides authobjects for the CRAM-MD5, PLAIN, and LOGIN mechanisms; they are named SMTP.auth_cram_md5, SMTP.auth_plain, and SMTP.auth_login respectively. They all require that the user and password properties of the SMTP instance are set to appropriate values.
User code does not normally need to call auth directly, but can instead call the login() method, which will try each of the above mechanisms in turn, in the order listed. auth is exposed to facilitate the implementation of authentication methods not (or not yet) supported directly by smtplib.
New in version 3.5.
Put the SMTP connection in TLS (Transport Layer Security) mode. All SMTP commands that follow will be encrypted. You should then call ehlo() again.
If keyfile and certfile are provided, they are used to create an ssl.SSLContext.
Optional context parameter is an ssl.SSLContext object; This is an alternative to using a keyfile and a certfile and if specified both keyfile and certfile should be None.
If there has been no previous EHLO or HELO command this session, this method tries ESMTP EHLO first.
Deprecated since version 3.6: keyfile and certfile are deprecated in favor of context. Please use ssl.SSLContext.load_cert_chain() instead, or let ssl.create_default_context() select the system’s trusted CA certificates for you.
The server didn’t reply properly to the HELO greeting.
The server does not support the STARTTLS extension.
SSL/TLS support is not available to your Python interpreter.
Changed in version 3.3: context was added.
Changed in version 3.4: The method now supports hostname check with SSLContext.check_hostname and Server Name Indicator (see HAS_SNI).
Changed in version 3.5: The error raised for lack of STARTTLS support is now the SMTPNotSupportedError subclass instead of the base SMTPException.
Send mail. The required arguments are an RFC 822 from-address string, a list of RFC 822 to-address strings (a bare string will be treated as a list with 1 address), and a message string. The caller may pass a list of ESMTP options (such as 8bitmime) to be used in MAIL FROM commands as mail_options. ESMTP options (such as DSN commands) that should be used with all RCPT commands can be passed as rcpt_options. (If you need to use different ESMTP options to different recipients you have to use the low-level methods such as mail(), rcpt() and data() to send the message.)
Note
The from_addr and to_addrs parameters are used to construct the message envelope used by the transport agents. sendmail does not modify the message headers in any way.
msg may be a string containing characters in the ASCII range, or a byte string. A string is encoded to bytes using the ascii codec, and lone \r and \n characters are converted to \r\n characters. A byte string is not modified.
If there has been no previous EHLO or HELO command this session, this method tries ESMTP EHLO first. If the server does ESMTP, message size and each of the specified options will be passed to it (if the option is in the feature set the server advertises). If EHLO fails, HELO will be tried and ESMTP options suppressed.
This method will return normally if the mail is accepted for at least one recipient. Otherwise it will raise an exception. That is, if this method does not raise an exception, then someone should get your mail. If this method does not raise an exception, it returns a dictionary, with one entry for each recipient that was refused. Each entry contains a tuple of the SMTP error code and the accompanying error message sent by the server.
If SMTPUTF8 is included in mail_options, and the server supports it, from_addr and to_addrs may contain non-ASCII characters.
This method may raise the following exceptions:
All recipients were refused. Nobody got the mail. The recipients attribute of the exception object is a dictionary with information about the refused recipients (like the one returned when at least one recipient was accepted).
The server didn’t reply properly to the HELO greeting.
The server didn’t accept the from_addr.
The server replied with an unexpected error code (other than a refusal of a recipient).
SMTPUTF8 was given in the mail_options but is not supported by the server.
Unless otherwise noted, the connection will be open even after an exception is raised.
Changed in version 3.2: msg may be a byte string.
Changed in version 3.5: SMTPUTF8 support added, and SMTPNotSupportedError may be raised if SMTPUTF8 is specified but the server does not support it.
This is a convenience method for calling sendmail() with the message represented by an email.message.Message object. The arguments have the same meaning as for sendmail(), except that msg is a Message object.
If from_addr is None or to_addrs is None, send_message fills those arguments with addresses extracted from the headers of msg as specified in RFC 5322: from_addr is set to the Sender field if it is present, and otherwise to the From field. to_addrs combines the values (if any) of the To, Cc, and Bcc fields from msg. If exactly one set of Resent-* headers appear in the message, the regular headers are ignored and the Resent-* headers are used instead. If the message contains more than one set of Resent-* headers, a ValueError is raised, since there is no way to unambiguously detect the most recent set of Resent- headers.
send_message serializes msg using BytesGenerator with \r\n as the linesep, and calls sendmail() to transmit the resulting message. Regardless of the values of from_addr and to_addrs, send_message does not transmit any Bcc or Resent-Bcc headers that may appear in msg. If any of the addresses in from_addr and to_addrs contain non-ASCII characters and the server does not advertise SMTPUTF8 support, an SMTPNotSupported error is raised. Otherwise the Message is serialized with a clone of its policy with the utf8 attribute set to True, and SMTPUTF8 and BODY=8BITMIME are added to mail_options.
New in version 3.2.
New in version 3.5: Support for internationalized addresses (SMTPUTF8).
Terminate the SMTP session and close the connection. Return the result of the SMTP QUIT command.
Low-level methods corresponding to the standard SMTP/ESMTP commands HELP, RSET, NOOP, MAIL, RCPT, and DATA are also supported. Normally these do not need to be called directly, so they are not documented here. For details, consult the module code.
This example prompts the user for addresses needed in the message envelope (‘To’ and ‘From’ addresses), and the message to be delivered. Note that the headers to be included with the message must be included in the message as entered; this example doesn’t do any processing of the RFC 822 headers. In particular, the ‘To’ and ‘From’ addresses must be included in the message headers explicitly.
Note
In general, you will want to use the email package’s features to construct an email message, which you can then send via send_message(); see email: Examples.


The LMTP protocol, which is very similar to ESMTP, is heavily based on the standard SMTP client. It’s common to use Unix sockets for LMTP, so our connect() method must support that as well as a regular host:port server. The optional arguments local_hostname and source_address have the same meaning as they do in the SMTP class. To specify a Unix socket, you must use an absolute path for host, starting with a ‘/’.
Authentication is supported, using the regular SMTP mechanism. When using a Unix socket, LMTP generally don’t support or require any authentication, but your mileage might vary.
Changed in version 3.9: The optional timeout parameter was added.


An SMTP instance encapsulates an SMTP connection. It has methods that support a full repertoire of SMTP and ESMTP operations. If the optional host and port parameters are given, the SMTP connect() method is called with those parameters during initialization. If specified, local_hostname is used as the FQDN of the local host in the HELO/EHLO command. Otherwise, the local hostname is found using socket.getfqdn(). If the connect() call returns anything other than a success code, an SMTPConnectError is raised. The optional timeout parameter specifies a timeout in seconds for blocking operations like the connection attempt (if not specified, the global default timeout setting will be used). If the timeout expires, socket.timeout is raised. The optional source_address parameter allows binding to some specific source address in a machine with multiple network interfaces, and/or to some specific source TCP port. It takes a 2-tuple (host, port), for the socket to bind to as its source address before connecting. If omitted (or if host or port are '' and/or 0 respectively) the OS default behavior will be used.
For normal use, you should only require the initialization/connect, sendmail(), and SMTP.quit() methods. An example is included below.
The SMTP class supports the with statement. When used like this, the SMTP QUIT command is issued automatically when the with statement exits. E.g.:
All commands will raise an auditing event smtplib.SMTP.send with arguments self and data, where data is the bytes about to be sent to the remote host.
Changed in version 3.3: Support for the with statement was added.
Changed in version 3.3: source_address argument was added.
New in version 3.5: The SMTPUTF8 extension (RFC 6531) is now supported.
Changed in version 3.9: If the timeout parameter is set to be zero, it will raise a ValueError to prevent the creation of a non-blocking socket


Issue an SMTP AUTH command for the specified authentication mechanism, and handle the challenge response via authobject.
mechanism specifies which authentication mechanism is to be used as argument to the AUTH command; the valid values are those listed in the auth element of esmtp_features.
authobject must be a callable object taking an optional single argument:
data = authobject(challenge=None)
If optional keyword argument initial_response_ok is true, authobject() will be called first with no argument. It can return the RFC 4954 “initial response” ASCII str which will be encoded and sent with the AUTH command as below. If the authobject() does not support an initial response (e.g. because it requires a challenge), it should return None when called with challenge=None. If initial_response_ok is false, then authobject() will not be called first with None.
If the initial response check returns None, or if initial_response_ok is false, authobject() will be called to process the server’s challenge response; the challenge argument it is passed will be a bytes. It should return ASCII str data that will be base64 encoded and sent to the server.
The SMTP class provides authobjects for the CRAM-MD5, PLAIN, and LOGIN mechanisms; they are named SMTP.auth_cram_md5, SMTP.auth_plain, and SMTP.auth_login respectively. They all require that the user and password properties of the SMTP instance are set to appropriate values.
User code does not normally need to call auth directly, but can instead call the login() method, which will try each of the above mechanisms in turn, in the order listed. auth is exposed to facilitate the implementation of authentication methods not (or not yet) supported directly by smtplib.
New in version 3.5.


Connect to a host on a given port. The defaults are to connect to the local host at the standard SMTP port (25). If the hostname ends with a colon (':') followed by a number, that suffix will be stripped off and the number interpreted as the port number to use. This method is automatically invoked by the constructor if a host is specified during instantiation. Returns a 2-tuple of the response code and message sent by the server in its connection response.
Raises an auditing event smtplib.connect with arguments self, host, port.


Send a command cmd to the server. The optional argument args is simply concatenated to the command, separated by a space.
This returns a 2-tuple composed of a numeric response code and the actual response line (multiline responses are joined into one long line.)
In normal operation it should not be necessary to call this method explicitly. It is used to implement other methods and may be useful for testing private extensions.
If the connection to the server is lost while waiting for the reply, SMTPServerDisconnected will be raised.


Identify yourself to an ESMTP server using EHLO. The hostname argument defaults to the fully qualified domain name of the local host. Examine the response for ESMTP option and store them for use by has_extn(). Also sets several informational attributes: the message returned by the server is stored as the ehlo_resp attribute, does_esmtp is set to true or false depending on whether the server supports ESMTP, and esmtp_features will be a dictionary containing the names of the SMTP service extensions this server supports, and their parameters (if any).
Unless you wish to use has_extn() before sending mail, it should not be necessary to call this method explicitly. It will be implicitly called by sendmail() when necessary.


This method calls ehlo() and/or helo() if there has been no previous EHLO or HELO command this session. It tries ESMTP EHLO first.
The server didn’t reply properly to the HELO greeting.


Return True if name is in the set of SMTP service extensions returned by the server, False otherwise. Case is ignored.


Identify yourself to the SMTP server using HELO. The hostname argument defaults to the fully qualified domain name of the local host. The message returned by the server is stored as the helo_resp attribute of the object.
In normal operation it should not be necessary to call this method explicitly. It will be implicitly called by the sendmail() when necessary.


Log in on an SMTP server that requires authentication. The arguments are the username and the password to authenticate with. If there has been no previous EHLO or HELO command this session, this method tries ESMTP EHLO first. This method will return normally if the authentication was successful, or may raise the following exceptions:
The server didn’t reply properly to the HELO greeting.
The server didn’t accept the username/password combination.
The AUTH command is not supported by the server.
No suitable authentication method was found.
Each of the authentication methods supported by smtplib are tried in turn if they are advertised as supported by the server. See auth() for a list of supported authentication methods. initial_response_ok is passed through to auth().
Optional keyword argument initial_response_ok specifies whether, for authentication methods that support it, an “initial response” as specified in RFC 4954 can be sent along with the AUTH command, rather than requiring a challenge/response.
Changed in version 3.5: SMTPNotSupportedError may be raised, and the initial_response_ok parameter was added.


Terminate the SMTP session and close the connection. Return the result of the SMTP QUIT command.


Send mail. The required arguments are an RFC 822 from-address string, a list of RFC 822 to-address strings (a bare string will be treated as a list with 1 address), and a message string. The caller may pass a list of ESMTP options (such as 8bitmime) to be used in MAIL FROM commands as mail_options. ESMTP options (such as DSN commands) that should be used with all RCPT commands can be passed as rcpt_options. (If you need to use different ESMTP options to different recipients you have to use the low-level methods such as mail(), rcpt() and data() to send the message.)
Note
The from_addr and to_addrs parameters are used to construct the message envelope used by the transport agents. sendmail does not modify the message headers in any way.
msg may be a string containing characters in the ASCII range, or a byte string. A string is encoded to bytes using the ascii codec, and lone \r and \n characters are converted to \r\n characters. A byte string is not modified.
If there has been no previous EHLO or HELO command this session, this method tries ESMTP EHLO first. If the server does ESMTP, message size and each of the specified options will be passed to it (if the option is in the feature set the server advertises). If EHLO fails, HELO will be tried and ESMTP options suppressed.
This method will return normally if the mail is accepted for at least one recipient. Otherwise it will raise an exception. That is, if this method does not raise an exception, then someone should get your mail. If this method does not raise an exception, it returns a dictionary, with one entry for each recipient that was refused. Each entry contains a tuple of the SMTP error code and the accompanying error message sent by the server.
If SMTPUTF8 is included in mail_options, and the server supports it, from_addr and to_addrs may contain non-ASCII characters.
This method may raise the following exceptions:
All recipients were refused. Nobody got the mail. The recipients attribute of the exception object is a dictionary with information about the refused recipients (like the one returned when at least one recipient was accepted).
The server didn’t reply properly to the HELO greeting.
The server didn’t accept the from_addr.
The server replied with an unexpected error code (other than a refusal of a recipient).
SMTPUTF8 was given in the mail_options but is not supported by the server.
Unless otherwise noted, the connection will be open even after an exception is raised.
Changed in version 3.2: msg may be a byte string.
Changed in version 3.5: SMTPUTF8 support added, and SMTPNotSupportedError may be raised if SMTPUTF8 is specified but the server does not support it.


This is a convenience method for calling sendmail() with the message represented by an email.message.Message object. The arguments have the same meaning as for sendmail(), except that msg is a Message object.
If from_addr is None or to_addrs is None, send_message fills those arguments with addresses extracted from the headers of msg as specified in RFC 5322: from_addr is set to the Sender field if it is present, and otherwise to the From field. to_addrs combines the values (if any) of the To, Cc, and Bcc fields from msg. If exactly one set of Resent-* headers appear in the message, the regular headers are ignored and the Resent-* headers are used instead. If the message contains more than one set of Resent-* headers, a ValueError is raised, since there is no way to unambiguously detect the most recent set of Resent- headers.
send_message serializes msg using BytesGenerator with \r\n as the linesep, and calls sendmail() to transmit the resulting message. Regardless of the values of from_addr and to_addrs, send_message does not transmit any Bcc or Resent-Bcc headers that may appear in msg. If any of the addresses in from_addr and to_addrs contain non-ASCII characters and the server does not advertise SMTPUTF8 support, an SMTPNotSupported error is raised. Otherwise the Message is serialized with a clone of its policy with the utf8 attribute set to True, and SMTPUTF8 and BODY=8BITMIME are added to mail_options.
New in version 3.2.
New in version 3.5: Support for internationalized addresses (SMTPUTF8).


Set the debug output level. A value of 1 or True for level results in debug messages for connection and for all messages sent to and received from the server. A value of 2 for level results in these messages being timestamped.
Changed in version 3.5: Added debuglevel 2.


Put the SMTP connection in TLS (Transport Layer Security) mode. All SMTP commands that follow will be encrypted. You should then call ehlo() again.
If keyfile and certfile are provided, they are used to create an ssl.SSLContext.
Optional context parameter is an ssl.SSLContext object; This is an alternative to using a keyfile and a certfile and if specified both keyfile and certfile should be None.
If there has been no previous EHLO or HELO command this session, this method tries ESMTP EHLO first.
Deprecated since version 3.6: keyfile and certfile are deprecated in favor of context. Please use ssl.SSLContext.load_cert_chain() instead, or let ssl.create_default_context() select the system’s trusted CA certificates for you.
The server didn’t reply properly to the HELO greeting.
The server does not support the STARTTLS extension.
SSL/TLS support is not available to your Python interpreter.
Changed in version 3.3: context was added.
Changed in version 3.4: The method now supports hostname check with SSLContext.check_hostname and Server Name Indicator (see HAS_SNI).
Changed in version 3.5: The error raised for lack of STARTTLS support is now the SMTPNotSupportedError subclass instead of the base SMTPException.


Check the validity of an address on this server using SMTP VRFY. Returns a tuple consisting of code 250 and a full RFC 822 address (including human name) if the user address is valid. Otherwise returns an SMTP error code of 400 or greater and an error string.
Note
Many sites disable SMTP VRFY in order to foil spammers.


SMTP authentication went wrong. Most probably the server didn’t accept the username/password combination provided.


Error occurred during establishment of a connection with the server.


The SMTP server refused to accept the message data.


Subclass of OSError that is the base exception class for all the other exceptions provided by this module.
Changed in version 3.4: SMTPException became subclass of OSError


The command or option attempted is not supported by the server.
New in version 3.5.


All recipient addresses refused. The errors for each recipient are accessible through the attribute recipients, which is a dictionary of exactly the same sort as SMTP.sendmail() returns.


Base class for all exceptions that include an SMTP error code. These exceptions are generated in some instances when the SMTP server returns an error code. The error code is stored in the smtp_code attribute of the error, and the smtp_error attribute is set to the error message.


Sender address refused. In addition to the attributes set by on all SMTPResponseException exceptions, this sets ‘sender’ to the string that the SMTP server refused.


This exception is raised when the server unexpectedly disconnects, or when an attempt is made to use the SMTP instance before connecting it to a server.


An SMTP_SSL instance behaves exactly the same as instances of SMTP. SMTP_SSL should be used for situations where SSL is required from the beginning of the connection and using starttls() is not appropriate. If host is not specified, the local host is used. If port is zero, the standard SMTP-over-SSL port (465) is used. The optional arguments local_hostname, timeout and source_address have the same meaning as they do in the SMTP class. context, also optional, can contain a SSLContext and allows configuring various aspects of the secure connection. Please read Security considerations for best practices.
keyfile and certfile are a legacy alternative to context, and can point to a PEM formatted private key and certificate chain file for the SSL connection.
Changed in version 3.3: context was added.
Changed in version 3.3: source_address argument was added.
Changed in version 3.4: The class now supports hostname check with ssl.SSLContext.check_hostname and Server Name Indication (see ssl.HAS_SNI).
Deprecated since version 3.6: keyfile and certfile are deprecated in favor of context. Please use ssl.SSLContext.load_cert_chain() instead, or let ssl.create_default_context() select the system’s trusted CA certificates for you.
Changed in version 3.9: If the timeout parameter is set to be zero, it will raise a ValueError to prevent the creation of a non-blocking socket


Source code: Lib/sndhdr.py
The sndhdr provides utility functions which attempt to determine the type of sound data which is in a file. When these functions are able to determine what type of sound data is stored in a file, they return a namedtuple(), containing five attributes: (filetype, framerate, nchannels, nframes, sampwidth). The value for type indicates the data type and will be one of the strings 'aifc', 'aiff', 'au', 'hcom', 'sndr', 'sndt', 'voc', 'wav', '8svx', 'sb', 'ub', or 'ul'. The sampling_rate will be either the actual value or 0 if unknown or difficult to decode. Similarly, channels will be either the number of channels or 0 if it cannot be determined or if the value is difficult to decode. The value for frames will be either the number of frames or -1. The last item in the tuple, bits_per_sample, will either be the sample size in bits or 'A' for A-LAW or 'U' for u-LAW.
Determines the type of sound data stored in the file filename using whathdr(). If it succeeds, returns a namedtuple as described above, otherwise None is returned.
Changed in version 3.5: Result changed from a tuple to a namedtuple.
Determines the type of sound data stored in a file based on the file header. The name of the file is given by filename. This function returns a namedtuple as described above on success, or None.
Changed in version 3.5: Result changed from a tuple to a namedtuple.


Determines the type of sound data stored in the file filename using whathdr(). If it succeeds, returns a namedtuple as described above, otherwise None is returned.
Changed in version 3.5: Result changed from a tuple to a namedtuple.


Determines the type of sound data stored in a file based on the file header. The name of the file is given by filename. This function returns a namedtuple as described above on success, or None.
Changed in version 3.5: Result changed from a tuple to a namedtuple.