New in version 3.3.
Source code: Lib/venv/
The venv module provides support for creating lightweight “virtual environments” with their own site directories, optionally isolated from system site directories. Each virtual environment has its own Python binary (which matches the version of the binary that was used to create this environment) and can have its own independent set of installed Python packages in its site directories.
See PEP 405 for more information about Python virtual environments.
See also
Python Packaging User Guide: Creating and using virtual environments
Creation of virtual environments is done by executing the command venv:
Running this command creates the target directory (creating any parent directories that don’t exist already) and places a pyvenv.cfg file in it with a home key pointing to the Python installation from which the command was run (a common name for the target directory is .venv). It also creates a bin (or Scripts on Windows) subdirectory containing a copy/symlink of the Python binary/binaries (as appropriate for the platform or arguments used at environment creation time). It also creates an (initially empty) lib/pythonX.Y/site-packages subdirectory (on Windows, this is Lib\site-packages). If an existing directory is specified, it will be re-used.
Deprecated since version 3.6: pyvenv was the recommended tool for creating virtual environments for Python 3.3 and 3.4, and is deprecated in Python 3.6.
Changed in version 3.5: The use of venv is now recommended for creating virtual environments.
On Windows, invoke the venv command as follows:
Alternatively, if you configured the PATH and PATHEXT variables for your Python installation:
The command, if run with -h, will show the available options:
Changed in version 3.9: Add --upgrade-deps option to upgrade pip + setuptools to the latest on PyPI
Changed in version 3.4: Installs pip by default, added the --without-pip and --copies options
Changed in version 3.4: In earlier versions, if the target directory already existed, an error was raised, unless the --clear or --upgrade option was provided.
Note
While symlinks are supported on Windows, they are not recommended. Of particular note is that double-clicking python.exe in File Explorer will resolve the symlink eagerly and ignore the virtual environment.
Note
On Microsoft Windows, it may be required to enable the Activate.ps1 script by setting the execution policy for the user. You can do this by issuing the following PowerShell command:
PS C:> Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
See About Execution Policies for more information.
The created pyvenv.cfg file also includes the include-system-site-packages key, set to true if venv is run with the --system-site-packages option, false otherwise.
Unless the --without-pip option is given, ensurepip will be invoked to bootstrap pip into the virtual environment.
Multiple paths can be given to venv, in which case an identical virtual environment will be created, according to the given options, at each provided path.
Once a virtual environment has been created, it can be “activated” using a script in the virtual environment’s binary directory. The invocation of the script is platform-specific (<venv> must be replaced by the path of the directory containing the virtual environment):
Platform
Shell
Command to activate virtual environment
POSIX
bash/zsh
$ source <venv>/bin/activate
fish
$ source <venv>/bin/activate.fish
csh/tcsh
$ source <venv>/bin/activate.csh
PowerShell Core
$ <venv>/bin/Activate.ps1
Windows
cmd.exe
C:\> <venv>\Scripts\activate.bat
PowerShell
PS C:\> <venv>\Scripts\Activate.ps1
When a virtual environment is active, the VIRTUAL_ENV environment variable is set to the path of the virtual environment. This can be used to check if one is running inside a virtual environment.
You don’t specifically need to activate an environment; activation just prepends the virtual environment’s binary directory to your path, so that “python” invokes the virtual environment’s Python interpreter and you can run installed scripts without having to use their full path. However, all scripts installed in a virtual environment should be runnable without activating it, and run with the virtual environment’s Python automatically.
You can deactivate a virtual environment by typing “deactivate” in your shell. The exact mechanism is platform-specific and is an internal implementation detail (typically a script or shell function will be used).
New in version 3.4: fish and csh activation scripts.
New in version 3.8: PowerShell activation scripts installed under POSIX for PowerShell Core support.
Note
A virtual environment is a Python environment such that the Python interpreter, libraries and scripts installed into it are isolated from those installed in other virtual environments, and (by default) any libraries installed in a “system” Python, i.e., one which is installed as part of your operating system.
A virtual environment is a directory tree which contains Python executable files and other files which indicate that it is a virtual environment.
Common installation tools such as setuptools and pip work as expected with virtual environments. In other words, when a virtual environment is active, they install Python packages into the virtual environment without needing to be told to do so explicitly.
When a virtual environment is active (i.e., the virtual environment’s Python interpreter is running), the attributes sys.prefix and sys.exec_prefix point to the base directory of the virtual environment, whereas sys.base_prefix and sys.base_exec_prefix point to the non-virtual environment Python installation which was used to create the virtual environment. If a virtual environment is not active, then sys.prefix is the same as sys.base_prefix and sys.exec_prefix is the same as sys.base_exec_prefix (they all point to a non-virtual environment Python installation).
When a virtual environment is active, any options that change the installation path will be ignored from all distutils configuration files to prevent projects being inadvertently installed outside of the virtual environment.
When working in a command shell, users can make a virtual environment active by running an activate script in the virtual environment’s executables directory (the precise filename and command to use the file is shell-dependent), which prepends the virtual environment’s directory for executables to the PATH environment variable for the running shell. There should be no need in other circumstances to activate a virtual environment; scripts installed into virtual environments have a “shebang” line which points to the virtual environment’s Python interpreter. This means that the script will run with that interpreter regardless of the value of PATH. On Windows, “shebang” line processing is supported if you have the Python Launcher for Windows installed (this was added to Python in 3.3 - see PEP 397 for more details). Thus, double-clicking an installed script in a Windows Explorer window should run the script with the correct interpreter without there needing to be any reference to its virtual environment in PATH.
The high-level method described above makes use of a simple API which provides mechanisms for third-party virtual environment creators to customize environment creation according to their needs, the EnvBuilder class.
The EnvBuilder class accepts the following keyword arguments on instantiation:
Changed in version 3.4: Added the with_pip parameter
New in version 3.6: Added the prompt parameter
New in version 3.9: Added the upgrade_deps parameter
Creators of third-party virtual environment tools will be free to use the provided EnvBuilder class as a base class.
The returned env-builder is an object which has a method, create:
Create a virtual environment by specifying the target directory (absolute or relative to the current directory) which is to contain the virtual environment. The create method will either create the environment in the specified directory, or raise an appropriate exception.
The create method of the EnvBuilder class illustrates the hooks available for subclass customization:
Each of the methods ensure_directories(), create_configuration(), setup_python(), setup_scripts() and post_setup() can be overridden.
Creates the environment directory and all necessary directories, and returns a context object. This is just a holder for attributes (such as paths), for use by the other methods. The directories are allowed to exist already, as long as either clear or upgrade were specified to allow operating on an existing environment directory.
Creates the pyvenv.cfg configuration file in the environment.
Creates a copy or symlink to the Python executable in the environment. On POSIX systems, if a specific executable python3.x was used, symlinks to python and python3 will be created pointing to that executable, unless files with those names already exist.
Installs activation scripts appropriate to the platform into the virtual environment.
Upgrades the core venv dependency packages (currently pip and setuptools) in the environment. This is done by shelling out to the pip executable in the environment.
New in version 3.9.
A placeholder method which can be overridden in third party implementations to pre-install packages in the virtual environment or perform other post-creation steps.
Changed in version 3.7.2: Windows now uses redirector scripts for python[w].exe instead of copying the actual binaries. In 3.7.2 only setup_python() does nothing unless running from a build in the source tree.
Changed in version 3.7.3: Windows copies the redirector scripts as part of setup_python() instead of setup_scripts(). This was not the case in 3.7.2. When using symlinks, the original executables will be linked.
In addition, EnvBuilder provides this utility method that can be called from setup_scripts() or post_setup() in subclasses to assist in installing custom scripts into the virtual environment.
path is the path to a directory that should contain subdirectories “common”, “posix”, “nt”, each containing scripts destined for the bin directory in the environment. The contents of “common” and the directory corresponding to os.name are copied after some text replacement of placeholders:
The directories are allowed to exist (for when an existing environment is being upgraded).
There is also a module-level convenience function:
Create an EnvBuilder with the given keyword arguments, and call its create() method with the env_dir argument.
New in version 3.3.
Changed in version 3.4: Added the with_pip parameter
Changed in version 3.6: Added the prompt parameter
The following script shows how to extend EnvBuilder by implementing a subclass which installs setuptools and pip into a created virtual environment:
This script is also available for download online.


Create an EnvBuilder with the given keyword arguments, and call its create() method with the env_dir argument.
New in version 3.3.
Changed in version 3.4: Added the with_pip parameter
Changed in version 3.6: Added the prompt parameter


The EnvBuilder class accepts the following keyword arguments on instantiation:
Changed in version 3.4: Added the with_pip parameter
New in version 3.6: Added the prompt parameter
New in version 3.9: Added the upgrade_deps parameter
Creators of third-party virtual environment tools will be free to use the provided EnvBuilder class as a base class.
The returned env-builder is an object which has a method, create:
Create a virtual environment by specifying the target directory (absolute or relative to the current directory) which is to contain the virtual environment. The create method will either create the environment in the specified directory, or raise an appropriate exception.
The create method of the EnvBuilder class illustrates the hooks available for subclass customization:
Each of the methods ensure_directories(), create_configuration(), setup_python(), setup_scripts() and post_setup() can be overridden.
Creates the environment directory and all necessary directories, and returns a context object. This is just a holder for attributes (such as paths), for use by the other methods. The directories are allowed to exist already, as long as either clear or upgrade were specified to allow operating on an existing environment directory.
Creates the pyvenv.cfg configuration file in the environment.
Creates a copy or symlink to the Python executable in the environment. On POSIX systems, if a specific executable python3.x was used, symlinks to python and python3 will be created pointing to that executable, unless files with those names already exist.
Installs activation scripts appropriate to the platform into the virtual environment.
Upgrades the core venv dependency packages (currently pip and setuptools) in the environment. This is done by shelling out to the pip executable in the environment.
New in version 3.9.
A placeholder method which can be overridden in third party implementations to pre-install packages in the virtual environment or perform other post-creation steps.
Changed in version 3.7.2: Windows now uses redirector scripts for python[w].exe instead of copying the actual binaries. In 3.7.2 only setup_python() does nothing unless running from a build in the source tree.
Changed in version 3.7.3: Windows copies the redirector scripts as part of setup_python() instead of setup_scripts(). This was not the case in 3.7.2. When using symlinks, the original executables will be linked.
In addition, EnvBuilder provides this utility method that can be called from setup_scripts() or post_setup() in subclasses to assist in installing custom scripts into the virtual environment.
path is the path to a directory that should contain subdirectories “common”, “posix”, “nt”, each containing scripts destined for the bin directory in the environment. The contents of “common” and the directory corresponding to os.name are copied after some text replacement of placeholders:
The directories are allowed to exist (for when an existing environment is being upgraded).


Create a virtual environment by specifying the target directory (absolute or relative to the current directory) which is to contain the virtual environment. The create method will either create the environment in the specified directory, or raise an appropriate exception.
The create method of the EnvBuilder class illustrates the hooks available for subclass customization:
Each of the methods ensure_directories(), create_configuration(), setup_python(), setup_scripts() and post_setup() can be overridden.


Creates the pyvenv.cfg configuration file in the environment.


Creates the environment directory and all necessary directories, and returns a context object. This is just a holder for attributes (such as paths), for use by the other methods. The directories are allowed to exist already, as long as either clear or upgrade were specified to allow operating on an existing environment directory.


path is the path to a directory that should contain subdirectories “common”, “posix”, “nt”, each containing scripts destined for the bin directory in the environment. The contents of “common” and the directory corresponding to os.name are copied after some text replacement of placeholders:
The directories are allowed to exist (for when an existing environment is being upgraded).


A placeholder method which can be overridden in third party implementations to pre-install packages in the virtual environment or perform other post-creation steps.


Creates a copy or symlink to the Python executable in the environment. On POSIX systems, if a specific executable python3.x was used, symlinks to python and python3 will be created pointing to that executable, unless files with those names already exist.


Installs activation scripts appropriate to the platform into the virtual environment.


Upgrades the core venv dependency packages (currently pip and setuptools) in the environment. This is done by shelling out to the pip executable in the environment.
New in version 3.9.


Source code: Lib/warnings.py
Warning messages are typically issued in situations where it is useful to alert the user of some condition in a program, where that condition (normally) doesn’t warrant raising an exception and terminating the program. For example, one might want to issue a warning when a program uses an obsolete module.
Python programmers issue warnings by calling the warn() function defined in this module. (C programmers use PyErr_WarnEx(); see Exception Handling for details).
Warning messages are normally written to sys.stderr, but their disposition can be changed flexibly, from ignoring all warnings to turning them into exceptions. The disposition of warnings can vary based on the warning category, the text of the warning message, and the source location where it is issued. Repetitions of a particular warning for the same source location are typically suppressed.
There are two stages in warning control: first, each time a warning is issued, a determination is made whether a message should be issued or not; next, if a message is to be issued, it is formatted and printed using a user-settable hook.
The determination whether to issue a warning message is controlled by the warning filter, which is a sequence of matching rules and actions. Rules can be added to the filter by calling filterwarnings() and reset to its default state by calling resetwarnings().
The printing of warning messages is done by calling showwarning(), which may be overridden; the default implementation of this function formats the message by calling formatwarning(), which is also available for use by custom implementations.
See also
logging.captureWarnings() allows you to handle all warnings with the standard logging infrastructure.
There are a number of built-in exceptions that represent warning categories. This categorization is useful to be able to filter out groups of warnings.
While these are technically built-in exceptions, they are documented here, because conceptually they belong to the warnings mechanism.
User code can define additional warning categories by subclassing one of the standard warning categories. A warning category must always be a subclass of the Warning class.
The following warnings category classes are currently defined:
Class
Description
Warning
This is the base class of all warning category classes. It is a subclass of Exception.
UserWarning
The default category for warn().
DeprecationWarning
Base category for warnings about deprecated features when those warnings are intended for other Python developers (ignored by default, unless triggered by code in __main__).
SyntaxWarning
Base category for warnings about dubious syntactic features.
RuntimeWarning
Base category for warnings about dubious runtime features.
FutureWarning
Base category for warnings about deprecated features when those warnings are intended for end users of applications that are written in Python.
PendingDeprecationWarning
Base category for warnings about features that will be deprecated in the future (ignored by default).
ImportWarning
Base category for warnings triggered during the process of importing a module (ignored by default).
UnicodeWarning
Base category for warnings related to Unicode.
BytesWarning
Base category for warnings related to bytes and bytearray.
ResourceWarning
Base category for warnings related to resource usage.
Changed in version 3.7: Previously DeprecationWarning and FutureWarning were distinguished based on whether a feature was being removed entirely or changing its behaviour. They are now distinguished based on their intended audience and the way they’re handled by the default warnings filters.
The warnings filter controls whether warnings are ignored, displayed, or turned into errors (raising an exception).
Conceptually, the warnings filter maintains an ordered list of filter specifications; any specific warning is matched against each filter specification in the list in turn until a match is found; the filter determines the disposition of the match. Each entry is a tuple of the form (action, message, category, module, lineno), where:
action is one of the following strings:
Value
Disposition
"default"
print the first occurrence of matching warnings for each location (module + line number) where the warning is issued
"error"
turn matching warnings into exceptions
"ignore"
never print matching warnings
"always"
always print matching warnings
"module"
print the first occurrence of matching warnings for each module where the warning is issued (regardless of line number)
"once"
print only the first occurrence of matching warnings, regardless of location
Since the Warning class is derived from the built-in Exception class, to turn a warning into an error we simply raise category(message).
If a warning is reported and doesn’t match any registered filter then the “default” action is applied (hence its name).
The warnings filter is initialized by -W options passed to the Python interpreter command line and the PYTHONWARNINGS environment variable. The interpreter saves the arguments for all supplied entries without interpretation in sys.warnoptions; the warnings module parses these when it is first imported (invalid options are ignored, after printing a message to sys.stderr).
Individual warnings filters are specified as a sequence of fields separated by colons:
The meaning of each of these fields is as described in The Warnings Filter. When listing multiple filters on a single line (as for PYTHONWARNINGS), the individual filters are separated by commas and the filters listed later take precedence over those listed before them (as they’re applied left-to-right, and the most recently applied filters take precedence over earlier ones).
Commonly used warning filters apply to either all warnings, warnings in a particular category, or warnings raised by particular modules or packages. Some examples:
By default, Python installs several warning filters, which can be overridden by the -W command-line option, the PYTHONWARNINGS environment variable and calls to filterwarnings().
In regular release builds, the default warning filter has the following entries (in order of precedence):
In debug builds, the list of default warning filters is empty.
Changed in version 3.2: DeprecationWarning is now ignored by default in addition to PendingDeprecationWarning.
Changed in version 3.7: DeprecationWarning is once again shown by default when triggered directly by code in __main__.
Changed in version 3.7: BytesWarning no longer appears in the default filter list and is instead configured via sys.warnoptions when -b is specified twice.
Developers of applications written in Python may wish to hide all Python level warnings from their users by default, and only display them when running tests or otherwise working on the application. The sys.warnoptions attribute used to pass filter configurations to the interpreter can be used as a marker to indicate whether or not warnings should be disabled:
Developers of test runners for Python code are advised to instead ensure that all warnings are displayed by default for the code under test, using code like:
Finally, developers of interactive shells that run user code in a namespace other than __main__ are advised to ensure that DeprecationWarning messages are made visible by default, using code like the following (where user_ns is the module used to execute code entered interactively):
If you are using code that you know will raise a warning, such as a deprecated function, but do not want to see the warning (even when warnings have been explicitly configured via the command line), then it is possible to suppress the warning using the catch_warnings context manager:
While within the context manager all warnings will simply be ignored. This allows you to use known-deprecated code without having to see the warning while not suppressing the warning for other code that might not be aware of its use of deprecated code. Note: this can only be guaranteed in a single-threaded application. If two or more threads use the catch_warnings context manager at the same time, the behavior is undefined.
To test warnings raised by code, use the catch_warnings context manager. With it you can temporarily mutate the warnings filter to facilitate your testing. For instance, do the following to capture all raised warnings to check:
One can also cause all warnings to be exceptions by using error instead of always. One thing to be aware of is that if a warning has already been raised because of a once/default rule, then no matter what filters are set the warning will not be seen again unless the warnings registry related to the warning has been cleared.
Once the context manager exits, the warnings filter is restored to its state when the context was entered. This prevents tests from changing the warnings filter in unexpected ways between tests and leading to indeterminate test results. The showwarning() function in the module is also restored to its original value. Note: this can only be guaranteed in a single-threaded application. If two or more threads use the catch_warnings context manager at the same time, the behavior is undefined.
When testing multiple operations that raise the same kind of warning, it is important to test them in a manner that confirms each operation is raising a new warning (e.g. set warnings to be raised as exceptions and check the operations raise exceptions, check that the length of the warning list continues to increase after each operation, or else delete the previous entries from the warnings list before each new operation).
Warning categories that are primarily of interest to Python developers (rather than end users of applications written in Python) are ignored by default.
Notably, this “ignored by default” list includes DeprecationWarning (for every module except __main__), which means developers should make sure to test their code with typically ignored warnings made visible in order to receive timely notifications of future breaking API changes (whether in the standard library or third party packages).
In the ideal case, the code will have a suitable test suite, and the test runner will take care of implicitly enabling all warnings when running tests (the test runner provided by the unittest module does this).
In less ideal cases, applications can be checked for use of deprecated interfaces by passing -Wd to the Python interpreter (this is shorthand for -W default) or setting PYTHONWARNINGS=default in the environment. This enables default handling for all warnings, including those that are ignored by default. To change what action is taken for encountered warnings you can change what argument is passed to -W (e.g. -W error). See the -W flag for more details on what is possible.
Issue a warning, or maybe ignore it or raise an exception. The category argument, if given, must be a warning category class; it defaults to UserWarning. Alternatively, message can be a Warning instance, in which case category will be ignored and message.__class__ will be used. In this case, the message text will be str(message). This function raises an exception if the particular warning issued is changed into an error by the warnings filter. The stacklevel argument can be used by wrapper functions written in Python, like this:
This makes the warning refer to deprecation()’s caller, rather than to the source of deprecation() itself (since the latter would defeat the purpose of the warning message).
source, if supplied, is the destroyed object which emitted a ResourceWarning.
Changed in version 3.6: Added source parameter.
This is a low-level interface to the functionality of warn(), passing in explicitly the message, category, filename and line number, and optionally the module name and the registry (which should be the __warningregistry__ dictionary of the module). The module name defaults to the filename with .py stripped; if no registry is passed, the warning is never suppressed. message must be a string and category a subclass of Warning or message may be a Warning instance, in which case category will be ignored.
module_globals, if supplied, should be the global namespace in use by the code for which the warning is issued. (This argument is used to support displaying source for modules found in zipfiles or other non-filesystem import sources).
source, if supplied, is the destroyed object which emitted a ResourceWarning.
Changed in version 3.6: Add the source parameter.
Write a warning to a file. The default implementation calls formatwarning(message, category, filename, lineno, line) and writes the resulting string to file, which defaults to sys.stderr. You may replace this function with any callable by assigning to warnings.showwarning. line is a line of source code to be included in the warning message; if line is not supplied, showwarning() will try to read the line specified by filename and lineno.
Format a warning the standard way. This returns a string which may contain embedded newlines and ends in a newline. line is a line of source code to be included in the warning message; if line is not supplied, formatwarning() will try to read the line specified by filename and lineno.
Insert an entry into the list of warnings filter specifications. The entry is inserted at the front by default; if append is true, it is inserted at the end. This checks the types of the arguments, compiles the message and module regular expressions, and inserts them as a tuple in the list of warnings filters. Entries closer to the front of the list override entries later in the list, if both match a particular warning. Omitted arguments default to a value that matches everything.
Insert a simple entry into the list of warnings filter specifications. The meaning of the function parameters is as for filterwarnings(), but regular expressions are not needed as the filter inserted always matches any message in any module as long as the category and line number match.
Reset the warnings filter. This discards the effect of all previous calls to filterwarnings(), including that of the -W command line options and calls to simplefilter().
A context manager that copies and, upon exit, restores the warnings filter and the showwarning() function. If the record argument is False (the default) the context manager returns None on entry. If record is True, a list is returned that is progressively populated with objects as seen by a custom showwarning() function (which also suppresses output to sys.stdout). Each object in the list has attributes with the same names as the arguments to showwarning().
The module argument takes a module that will be used instead of the module returned when you import warnings whose filter will be protected. This argument exists primarily for testing the warnings module itself.
Note
The catch_warnings manager works by replacing and then later restoring the module’s showwarning() function and internal list of filter specifications. This means the context manager is modifying global state and therefore is not thread-safe.


A context manager that copies and, upon exit, restores the warnings filter and the showwarning() function. If the record argument is False (the default) the context manager returns None on entry. If record is True, a list is returned that is progressively populated with objects as seen by a custom showwarning() function (which also suppresses output to sys.stdout). Each object in the list has attributes with the same names as the arguments to showwarning().
The module argument takes a module that will be used instead of the module returned when you import warnings whose filter will be protected. This argument exists primarily for testing the warnings module itself.
Note
The catch_warnings manager works by replacing and then later restoring the module’s showwarning() function and internal list of filter specifications. This means the context manager is modifying global state and therefore is not thread-safe.


Insert an entry into the list of warnings filter specifications. The entry is inserted at the front by default; if append is true, it is inserted at the end. This checks the types of the arguments, compiles the message and module regular expressions, and inserts them as a tuple in the list of warnings filters. Entries closer to the front of the list override entries later in the list, if both match a particular warning. Omitted arguments default to a value that matches everything.


Format a warning the standard way. This returns a string which may contain embedded newlines and ends in a newline. line is a line of source code to be included in the warning message; if line is not supplied, formatwarning() will try to read the line specified by filename and lineno.


Reset the warnings filter. This discards the effect of all previous calls to filterwarnings(), including that of the -W command line options and calls to simplefilter().


Write a warning to a file. The default implementation calls formatwarning(message, category, filename, lineno, line) and writes the resulting string to file, which defaults to sys.stderr. You may replace this function with any callable by assigning to warnings.showwarning. line is a line of source code to be included in the warning message; if line is not supplied, showwarning() will try to read the line specified by filename and lineno.


Insert a simple entry into the list of warnings filter specifications. The meaning of the function parameters is as for filterwarnings(), but regular expressions are not needed as the filter inserted always matches any message in any module as long as the category and line number match.


Issue a warning, or maybe ignore it or raise an exception. The category argument, if given, must be a warning category class; it defaults to UserWarning. Alternatively, message can be a Warning instance, in which case category will be ignored and message.__class__ will be used. In this case, the message text will be str(message). This function raises an exception if the particular warning issued is changed into an error by the warnings filter. The stacklevel argument can be used by wrapper functions written in Python, like this:
This makes the warning refer to deprecation()’s caller, rather than to the source of deprecation() itself (since the latter would defeat the purpose of the warning message).
source, if supplied, is the destroyed object which emitted a ResourceWarning.
Changed in version 3.6: Added source parameter.


This is a low-level interface to the functionality of warn(), passing in explicitly the message, category, filename and line number, and optionally the module name and the registry (which should be the __warningregistry__ dictionary of the module). The module name defaults to the filename with .py stripped; if no registry is passed, the warning is never suppressed. message must be a string and category a subclass of Warning or message may be a Warning instance, in which case category will be ignored.
module_globals, if supplied, should be the global namespace in use by the code for which the warning is issued. (This argument is used to support displaying source for modules found in zipfiles or other non-filesystem import sources).
source, if supplied, is the destroyed object which emitted a ResourceWarning.
Changed in version 3.6: Add the source parameter.


Source code: Lib/wave.py
The wave module provides a convenient interface to the WAV sound format. It does not support compression/decompression, but it does support mono/stereo.
The wave module defines the following function and exception:
If file is a string, open the file by that name, otherwise treat it as a file-like object. mode can be:
Read only mode.
Write only mode.
Note that it does not allow read/write WAV files.
A mode of 'rb' returns a Wave_read object, while a mode of 'wb' returns a Wave_write object. If mode is omitted and a file-like object is passed as file, file.mode is used as the default value for mode.
If you pass in a file-like object, the wave object will not close it when its close() method is called; it is the caller’s responsibility to close the file object.
The open() function may be used in a with statement. When the with block completes, the Wave_read.close() or Wave_write.close() method is called.
Changed in version 3.4: Added support for unseekable files.
An error raised when something is impossible because it violates the WAV specification or hits an implementation deficiency.
Wave_read objects, as returned by open(), have the following methods:
Close the stream if it was opened by wave, and make the instance unusable. This is called automatically on object collection.
Returns number of audio channels (1 for mono, 2 for stereo).
Returns sample width in bytes.
Returns sampling frequency.
Returns number of audio frames.
Returns compression type ('NONE' is the only supported type).
Human-readable version of getcomptype(). Usually 'not compressed' parallels 'NONE'.
Returns a namedtuple() (nchannels, sampwidth,
framerate, nframes, comptype, compname), equivalent to output of the get*() methods.
Reads and returns at most n frames of audio, as a bytes object.
Rewind the file pointer to the beginning of the audio stream.
The following two methods are defined for compatibility with the aifc module, and don’t do anything interesting.
Returns None.
Raise an error.
The following two methods define a term “position” which is compatible between them, and is otherwise implementation dependent.
Set the file pointer to the specified position.
Return current file pointer position.
For seekable output streams, the wave header will automatically be updated to reflect the number of frames actually written. For unseekable streams, the nframes value must be accurate when the first frame data is written. An accurate nframes value can be achieved either by calling setnframes() or setparams() with the number of frames that will be written before close() is called and then using writeframesraw() to write the frame data, or by calling writeframes() with all of the frame data to be written. In the latter case writeframes() will calculate the number of frames in the data and set nframes accordingly before writing the frame data.
Wave_write objects, as returned by open(), have the following methods:
Changed in version 3.4: Added support for unseekable files.
Make sure nframes is correct, and close the file if it was opened by wave. This method is called upon object collection. It will raise an exception if the output stream is not seekable and nframes does not match the number of frames actually written.
Set the number of channels.
Set the sample width to n bytes.
Set the frame rate to n.
Changed in version 3.2: A non-integral input to this method is rounded to the nearest integer.
Set the number of frames to n. This will be changed later if the number of frames actually written is different (this update attempt will raise an error if the output stream is not seekable).
Set the compression type and description. At the moment, only compression type NONE is supported, meaning no compression.
The tuple should be (nchannels, sampwidth, framerate, nframes, comptype,
compname), with values valid for the set*() methods. Sets all parameters.
Return current position in the file, with the same disclaimer for the Wave_read.tell() and Wave_read.setpos() methods.
Write audio frames, without correcting nframes.
Changed in version 3.4: Any bytes-like object is now accepted.
Write audio frames and make sure nframes is correct. It will raise an error if the output stream is not seekable and the total number of frames that have been written after data has been written does not match the previously set value for nframes.
Changed in version 3.4: Any bytes-like object is now accepted.
Note that it is invalid to set any parameters after calling writeframes() or writeframesraw(), and any attempt to do so will raise wave.Error.


An error raised when something is impossible because it violates the WAV specification or hits an implementation deficiency.


If file is a string, open the file by that name, otherwise treat it as a file-like object. mode can be:
Read only mode.
Write only mode.
Note that it does not allow read/write WAV files.
A mode of 'rb' returns a Wave_read object, while a mode of 'wb' returns a Wave_write object. If mode is omitted and a file-like object is passed as file, file.mode is used as the default value for mode.
If you pass in a file-like object, the wave object will not close it when its close() method is called; it is the caller’s responsibility to close the file object.
The open() function may be used in a with statement. When the with block completes, the Wave_read.close() or Wave_write.close() method is called.
Changed in version 3.4: Added support for unseekable files.


Close the stream if it was opened by wave, and make the instance unusable. This is called automatically on object collection.


Human-readable version of getcomptype(). Usually 'not compressed' parallels 'NONE'.


Returns compression type ('NONE' is the only supported type).


Returns number of audio channels (1 for mono, 2 for stereo).


Returns a namedtuple() (nchannels, sampwidth,
framerate, nframes, comptype, compname), equivalent to output of the get*() methods.


Reads and returns at most n frames of audio, as a bytes object.


Rewind the file pointer to the beginning of the audio stream.


Set the file pointer to the specified position.


Make sure nframes is correct, and close the file if it was opened by wave. This method is called upon object collection. It will raise an exception if the output stream is not seekable and nframes does not match the number of frames actually written.


Set the compression type and description. At the moment, only compression type NONE is supported, meaning no compression.


Set the frame rate to n.
Changed in version 3.2: A non-integral input to this method is rounded to the nearest integer.


Set the number of frames to n. This will be changed later if the number of frames actually written is different (this update attempt will raise an error if the output stream is not seekable).


The tuple should be (nchannels, sampwidth, framerate, nframes, comptype,
compname), with values valid for the set*() methods. Sets all parameters.


Return current position in the file, with the same disclaimer for the Wave_read.tell() and Wave_read.setpos() methods.


Write audio frames and make sure nframes is correct. It will raise an error if the output stream is not seekable and the total number of frames that have been written after data has been written does not match the previously set value for nframes.
Changed in version 3.4: Any bytes-like object is now accepted.


Write audio frames, without correcting nframes.
Changed in version 3.4: Any bytes-like object is now accepted.


Source code: Lib/weakref.py
The weakref module allows the Python programmer to create weak references to objects.
In the following, the term referent means the object which is referred to by a weak reference.
A weak reference to an object is not enough to keep the object alive: when the only remaining references to a referent are weak references, garbage collection is free to destroy the referent and reuse its memory for something else. However, until the object is actually destroyed the weak reference may return the object even if there are no strong references to it.
A primary use for weak references is to implement caches or mappings holding large objects, where it’s desired that a large object not be kept alive solely because it appears in a cache or mapping.
For example, if you have a number of large binary image objects, you may wish to associate a name with each. If you used a Python dictionary to map names to images, or images to names, the image objects would remain alive just because they appeared as values or keys in the dictionaries. The WeakKeyDictionary and WeakValueDictionary classes supplied by the weakref module are an alternative, using weak references to construct mappings that don’t keep objects alive solely because they appear in the mapping objects. If, for example, an image object is a value in a WeakValueDictionary, then when the last remaining references to that image object are the weak references held by weak mappings, garbage collection can reclaim the object, and its corresponding entries in weak mappings are simply deleted.
WeakKeyDictionary and WeakValueDictionary use weak references in their implementation, setting up callback functions on the weak references that notify the weak dictionaries when a key or value has been reclaimed by garbage collection. WeakSet implements the set interface, but keeps weak references to its elements, just like a WeakKeyDictionary does.
finalize provides a straight forward way to register a cleanup function to be called when an object is garbage collected. This is simpler to use than setting up a callback function on a raw weak reference, since the module automatically ensures that the finalizer remains alive until the object is collected.
Most programs should find that using one of these weak container types or finalize is all they need – it’s not usually necessary to create your own weak references directly. The low-level machinery is exposed by the weakref module for the benefit of advanced uses.
Not all objects can be weakly referenced; those objects which can include class instances, functions written in Python (but not in C), instance methods, sets, frozensets, some file objects, generators, type objects, sockets, arrays, deques, regular expression pattern objects, and code objects.
Changed in version 3.2: Added support for thread.lock, threading.Lock, and code objects.
Several built-in types such as list and dict do not directly support weak references but can add support through subclassing:
CPython implementation detail: Other built-in types such as tuple and int do not support weak references even when subclassed.
Extension types can easily be made to support weak references; see Weak Reference Support.
Return a weak reference to object. The original object can be retrieved by calling the reference object if the referent is still alive; if the referent is no longer alive, calling the reference object will cause None to be returned. If callback is provided and not None, and the returned weakref object is still alive, the callback will be called when the object is about to be finalized; the weak reference object will be passed as the only parameter to the callback; the referent will no longer be available.
It is allowable for many weak references to be constructed for the same object. Callbacks registered for each weak reference will be called from the most recently registered callback to the oldest registered callback.
Exceptions raised by the callback will be noted on the standard error output, but cannot be propagated; they are handled in exactly the same way as exceptions raised from an object’s __del__() method.
Weak references are hashable if the object is hashable. They will maintain their hash value even after the object was deleted. If hash() is called the first time only after the object was deleted, the call will raise TypeError.
Weak references support tests for equality, but not ordering. If the referents are still alive, two references have the same equality relationship as their referents (regardless of the callback). If either referent has been deleted, the references are equal only if the reference objects are the same object.
This is a subclassable type rather than a factory function.
This read-only attribute returns the callback currently associated to the weakref. If there is no callback or if the referent of the weakref is no longer alive then this attribute will have value None.
Changed in version 3.4: Added the __callback__ attribute.
Return a proxy to object which uses a weak reference. This supports use of the proxy in most contexts instead of requiring the explicit dereferencing used with weak reference objects. The returned object will have a type of either ProxyType or CallableProxyType, depending on whether object is callable. Proxy objects are not hashable regardless of the referent; this avoids a number of problems related to their fundamentally mutable nature, and prevent their use as dictionary keys. callback is the same as the parameter of the same name to the ref() function.
Changed in version 3.8: Extended the operator support on proxy objects to include the matrix multiplication operators @ and @=.
Return the number of weak references and proxies which refer to object.
Return a list of all weak reference and proxy objects which refer to object.
Mapping class that references keys weakly. Entries in the dictionary will be discarded when there is no longer a strong reference to the key. This can be used to associate additional data with an object owned by other parts of an application without adding attributes to those objects. This can be especially useful with objects that override attribute accesses.
Changed in version 3.9: Added support for | and |= operators, specified in PEP 584.
WeakKeyDictionary objects have an additional method that exposes the internal references directly. The references are not guaranteed to be “live” at the time they are used, so the result of calling the references needs to be checked before being used. This can be used to avoid creating references that will cause the garbage collector to keep the keys around longer than needed.
Return an iterable of the weak references to the keys.
Mapping class that references values weakly. Entries in the dictionary will be discarded when no strong reference to the value exists any more.
Changed in version 3.9: Added support for | and |= operators, as specified in PEP 584.
WeakValueDictionary objects have an additional method that has the same issues as the keyrefs() method of WeakKeyDictionary objects.
Return an iterable of the weak references to the values.
Set class that keeps weak references to its elements. An element will be discarded when no strong reference to it exists any more.
A custom ref subclass which simulates a weak reference to a bound method (i.e., a method defined on a class and looked up on an instance). Since a bound method is ephemeral, a standard weak reference cannot keep hold of it. WeakMethod has special code to recreate the bound method until either the object or the original function dies:
New in version 3.4.
Return a callable finalizer object which will be called when obj is garbage collected. Unlike an ordinary weak reference, a finalizer will always survive until the reference object is collected, greatly simplifying lifecycle management.
A finalizer is considered alive until it is called (either explicitly or at garbage collection), and after that it is dead. Calling a live finalizer returns the result of evaluating func(*arg, **kwargs), whereas calling a dead finalizer returns None.
Exceptions raised by finalizer callbacks during garbage collection will be shown on the standard error output, but cannot be propagated. They are handled in the same way as exceptions raised from an object’s __del__() method or a weak reference’s callback.
When the program exits, each remaining live finalizer is called unless its atexit attribute has been set to false. They are called in reverse order of creation.
A finalizer will never invoke its callback during the later part of the interpreter shutdown when module globals are liable to have been replaced by None.
If self is alive then mark it as dead and return the result of calling func(*args, **kwargs). If self is dead then return None.
If self is alive then mark it as dead and return the tuple (obj, func, args, kwargs). If self is dead then return None.
If self is alive then return the tuple (obj, func, args,
kwargs). If self is dead then return None.
Property which is true if the finalizer is alive, false otherwise.
A writable boolean property which by default is true. When the program exits, it calls all remaining live finalizers for which atexit is true. They are called in reverse order of creation.
Note
It is important to ensure that func, args and kwargs do not own any references to obj, either directly or indirectly, since otherwise obj will never be garbage collected. In particular, func should not be a bound method of obj.
New in version 3.4.
The type object for weak references objects.
The type object for proxies of objects which are not callable.
The type object for proxies of callable objects.
Sequence containing all the type objects for proxies. This can make it simpler to test if an object is a proxy without being dependent on naming both proxy types.
See also
The proposal and rationale for this feature, including links to earlier implementations and information about similar features in other languages.
Weak reference objects have no methods and no attributes besides ref.__callback__. A weak reference object allows the referent to be obtained, if it still exists, by calling it:
If the referent no longer exists, calling the reference object returns None:
Testing that a weak reference object is still live should be done using the expression ref() is not None. Normally, application code that needs to use a reference object should follow this pattern:
Using a separate test for “liveness” creates race conditions in threaded applications; another thread can cause a weak reference to become invalidated before the weak reference is called; the idiom shown above is safe in threaded applications as well as single-threaded applications.
Specialized versions of ref objects can be created through subclassing. This is used in the implementation of the WeakValueDictionary to reduce the memory overhead for each entry in the mapping. This may be most useful to associate additional information with a reference, but could also be used to insert additional processing on calls to retrieve the referent.
This example shows how a subclass of ref can be used to store additional information about an object and affect the value that’s returned when the referent is accessed:
This simple example shows how an application can use object IDs to retrieve objects that it has seen before. The IDs of the objects can then be used in other data structures without forcing the objects to remain alive, but the objects can still be retrieved by ID if they do.
The main benefit of using finalize is that it makes it simple to register a callback without needing to preserve the returned finalizer object. For instance
The finalizer can be called directly as well. However the finalizer will invoke the callback at most once.
You can unregister a finalizer using its detach() method. This kills the finalizer and returns the arguments passed to the constructor when it was created.
Unless you set the atexit attribute to False, a finalizer will be called when the program exits if it is still alive. For instance
Suppose we want to create a class whose instances represent temporary directories. The directories should be deleted with their contents when the first of the following events occurs:
We might try to implement the class using a __del__() method as follows:
Starting with Python 3.4, __del__() methods no longer prevent reference cycles from being garbage collected, and module globals are no longer forced to None during interpreter shutdown. So this code should work without any issues on CPython.
However, handling of __del__() methods is notoriously implementation specific, since it depends on internal details of the interpreter’s garbage collector implementation.
A more robust alternative can be to define a finalizer which only references the specific functions and objects that it needs, rather than having access to the full state of the object:
Defined like this, our finalizer only receives a reference to the details it needs to clean up the directory appropriately. If the object never gets garbage collected the finalizer will still be called at exit.
The other advantage of weakref based finalizers is that they can be used to register finalizers for classes where the definition is controlled by a third party, such as running code when a module is unloaded:
Note
If you create a finalizer object in a daemonic thread just as the program exits then there is the possibility that the finalizer does not get called at exit. However, in a daemonic thread atexit.register(), try: ... finally: ... and with: ... do not guarantee that cleanup occurs either.


The type object for proxies of callable objects.


Return a callable finalizer object which will be called when obj is garbage collected. Unlike an ordinary weak reference, a finalizer will always survive until the reference object is collected, greatly simplifying lifecycle management.
A finalizer is considered alive until it is called (either explicitly or at garbage collection), and after that it is dead. Calling a live finalizer returns the result of evaluating func(*arg, **kwargs), whereas calling a dead finalizer returns None.
Exceptions raised by finalizer callbacks during garbage collection will be shown on the standard error output, but cannot be propagated. They are handled in the same way as exceptions raised from an object’s __del__() method or a weak reference’s callback.
When the program exits, each remaining live finalizer is called unless its atexit attribute has been set to false. They are called in reverse order of creation.
A finalizer will never invoke its callback during the later part of the interpreter shutdown when module globals are liable to have been replaced by None.
If self is alive then mark it as dead and return the result of calling func(*args, **kwargs). If self is dead then return None.
If self is alive then mark it as dead and return the tuple (obj, func, args, kwargs). If self is dead then return None.
If self is alive then return the tuple (obj, func, args,
kwargs). If self is dead then return None.
Property which is true if the finalizer is alive, false otherwise.
A writable boolean property which by default is true. When the program exits, it calls all remaining live finalizers for which atexit is true. They are called in reverse order of creation.
Note
It is important to ensure that func, args and kwargs do not own any references to obj, either directly or indirectly, since otherwise obj will never be garbage collected. In particular, func should not be a bound method of obj.
New in version 3.4.


Property which is true if the finalizer is alive, false otherwise.


A writable boolean property which by default is true. When the program exits, it calls all remaining live finalizers for which atexit is true. They are called in reverse order of creation.


If self is alive then mark it as dead and return the tuple (obj, func, args, kwargs). If self is dead then return None.


If self is alive then return the tuple (obj, func, args,
kwargs). If self is dead then return None.


If self is alive then mark it as dead and return the result of calling func(*args, **kwargs). If self is dead then return None.


Return the number of weak references and proxies which refer to object.


Return a list of all weak reference and proxy objects which refer to object.


Return a proxy to object which uses a weak reference. This supports use of the proxy in most contexts instead of requiring the explicit dereferencing used with weak reference objects. The returned object will have a type of either ProxyType or CallableProxyType, depending on whether object is callable. Proxy objects are not hashable regardless of the referent; this avoids a number of problems related to their fundamentally mutable nature, and prevent their use as dictionary keys. callback is the same as the parameter of the same name to the ref() function.
Changed in version 3.8: Extended the operator support on proxy objects to include the matrix multiplication operators @ and @=.


The type object for proxies of objects which are not callable.


Sequence containing all the type objects for proxies. This can make it simpler to test if an object is a proxy without being dependent on naming both proxy types.


Return a weak reference to object. The original object can be retrieved by calling the reference object if the referent is still alive; if the referent is no longer alive, calling the reference object will cause None to be returned. If callback is provided and not None, and the returned weakref object is still alive, the callback will be called when the object is about to be finalized; the weak reference object will be passed as the only parameter to the callback; the referent will no longer be available.
It is allowable for many weak references to be constructed for the same object. Callbacks registered for each weak reference will be called from the most recently registered callback to the oldest registered callback.
Exceptions raised by the callback will be noted on the standard error output, but cannot be propagated; they are handled in exactly the same way as exceptions raised from an object’s __del__() method.
Weak references are hashable if the object is hashable. They will maintain their hash value even after the object was deleted. If hash() is called the first time only after the object was deleted, the call will raise TypeError.
Weak references support tests for equality, but not ordering. If the referents are still alive, two references have the same equality relationship as their referents (regardless of the callback). If either referent has been deleted, the references are equal only if the reference objects are the same object.
This is a subclassable type rather than a factory function.
This read-only attribute returns the callback currently associated to the weakref. If there is no callback or if the referent of the weakref is no longer alive then this attribute will have value None.
Changed in version 3.4: Added the __callback__ attribute.


This read-only attribute returns the callback currently associated to the weakref. If there is no callback or if the referent of the weakref is no longer alive then this attribute will have value None.


The type object for weak references objects.


Mapping class that references keys weakly. Entries in the dictionary will be discarded when there is no longer a strong reference to the key. This can be used to associate additional data with an object owned by other parts of an application without adding attributes to those objects. This can be especially useful with objects that override attribute accesses.
Changed in version 3.9: Added support for | and |= operators, specified in PEP 584.


Return an iterable of the weak references to the keys.


A custom ref subclass which simulates a weak reference to a bound method (i.e., a method defined on a class and looked up on an instance). Since a bound method is ephemeral, a standard weak reference cannot keep hold of it. WeakMethod has special code to recreate the bound method until either the object or the original function dies:
New in version 3.4.


Set class that keeps weak references to its elements. An element will be discarded when no strong reference to it exists any more.


Mapping class that references values weakly. Entries in the dictionary will be discarded when no strong reference to the value exists any more.
Changed in version 3.9: Added support for | and |= operators, as specified in PEP 584.


Return an iterable of the weak references to the values.


Source code: Lib/webbrowser.py
The webbrowser module provides a high-level interface to allow displaying Web-based documents to users. Under most circumstances, simply calling the open() function from this module will do the right thing.
Under Unix, graphical browsers are preferred under X11, but text-mode browsers will be used if graphical browsers are not available or an X11 display isn’t available. If text-mode browsers are used, the calling process will block until the user exits the browser.
If the environment variable BROWSER exists, it is interpreted as the os.pathsep-separated list of browsers to try ahead of the platform defaults. When the value of a list part contains the string %s, then it is interpreted as a literal browser command line to be used with the argument URL substituted for %s; if the part does not contain %s, it is simply interpreted as the name of the browser to launch. 1
For non-Unix platforms, or when a remote browser is available on Unix, the controlling process will not wait for the user to finish with the browser, but allow the remote browser to maintain its own windows on the display. If remote browsers are not available on Unix, the controlling process will launch a new browser and wait.
The script webbrowser can be used as a command-line interface for the module. It accepts a URL as the argument. It accepts the following optional parameters: -n opens the URL in a new browser window, if possible; -t opens the URL in a new browser page (“tab”). The options are, naturally, mutually exclusive. Usage example:
The following exception is defined:
Exception raised when a browser control error occurs.
The following functions are defined:
Display url using the default browser. If new is 0, the url is opened in the same browser window if possible. If new is 1, a new browser window is opened if possible. If new is 2, a new browser page (“tab”) is opened if possible. If autoraise is True, the window is raised if possible (note that under many window managers this will occur regardless of the setting of this variable).
Note that on some platforms, trying to open a filename using this function, may work and start the operating system’s associated program. However, this is neither supported nor portable.
Raises an auditing event webbrowser.open with argument url.
Open url in a new window of the default browser, if possible, otherwise, open url in the only browser window.
Open url in a new page (“tab”) of the default browser, if possible, otherwise equivalent to open_new().
Return a controller object for the browser type using. If using is None, return a controller for a default browser appropriate to the caller’s environment.
Register the browser type name. Once a browser type is registered, the get() function can return a controller for that browser type. If instance is not provided, or is None, constructor will be called without parameters to create an instance when needed. If instance is provided, constructor will never be called, and may be None.
Setting preferred to True makes this browser a preferred result for a get() call with no argument. Otherwise, this entry point is only useful if you plan to either set the BROWSER variable or call get() with a nonempty argument matching the name of a handler you declare.
Changed in version 3.7: preferred keyword-only parameter was added.
A number of browser types are predefined. This table gives the type names that may be passed to the get() function and the corresponding instantiations for the controller classes, all defined in this module.
Type Name
Class Name
Notes
'mozilla'
Mozilla('mozilla')
'firefox'
Mozilla('mozilla')
'netscape'
Mozilla('netscape')
'galeon'
Galeon('galeon')
'epiphany'
Galeon('epiphany')
'skipstone'
BackgroundBrowser('skipstone')
'kfmclient'
Konqueror()
(1)
'konqueror'
Konqueror()
(1)
'kfm'
Konqueror()
(1)
'mosaic'
BackgroundBrowser('mosaic')
'opera'
Opera()
'grail'
Grail()
'links'
GenericBrowser('links')
'elinks'
Elinks('elinks')
'lynx'
GenericBrowser('lynx')
'w3m'
GenericBrowser('w3m')
'windows-default'
WindowsDefault
(2)
'macosx'
MacOSX('default')
(3)
'safari'
MacOSX('safari')
(3)
'google-chrome'
Chrome('google-chrome')
'chrome'
Chrome('chrome')
'chromium'
Chromium('chromium')
'chromium-browser'
Chromium('chromium-browser')
Notes:
New in version 3.3: Support for Chrome/Chromium has been added.
Here are some simple examples:
Browser controllers provide these methods which parallel three of the module-level convenience functions:
Display url using the browser handled by this controller. If new is 1, a new browser window is opened if possible. If new is 2, a new browser page (“tab”) is opened if possible.
Open url in a new window of the browser handled by this controller, if possible, otherwise, open url in the only browser window. Alias open_new().
Open url in a new page (“tab”) of the browser handled by this controller, if possible, otherwise equivalent to open_new().
Executables named here without a full path will be searched in the directories given in the PATH environment variable.


Display url using the browser handled by this controller. If new is 1, a new browser window is opened if possible. If new is 2, a new browser page (“tab”) is opened if possible.


Open url in a new window of the browser handled by this controller, if possible, otherwise, open url in the only browser window. Alias open_new().


Open url in a new page (“tab”) of the browser handled by this controller, if possible, otherwise equivalent to open_new().


Exception raised when a browser control error occurs.


Return a controller object for the browser type using. If using is None, return a controller for a default browser appropriate to the caller’s environment.


Display url using the default browser. If new is 0, the url is opened in the same browser window if possible. If new is 1, a new browser window is opened if possible. If new is 2, a new browser page (“tab”) is opened if possible. If autoraise is True, the window is raised if possible (note that under many window managers this will occur regardless of the setting of this variable).
Note that on some platforms, trying to open a filename using this function, may work and start the operating system’s associated program. However, this is neither supported nor portable.
Raises an auditing event webbrowser.open with argument url.


Open url in a new window of the default browser, if possible, otherwise, open url in the only browser window.


Open url in a new page (“tab”) of the default browser, if possible, otherwise equivalent to open_new().


Register the browser type name. Once a browser type is registered, the get() function can return a controller for that browser type. If instance is not provided, or is None, constructor will be called without parameters to create an instance when needed. If instance is provided, constructor will never be called, and may be None.
Setting preferred to True makes this browser a preferred result for a get() call with no argument. Otherwise, this entry point is only useful if you plan to either set the BROWSER variable or call get() with a nonempty argument matching the name of a handler you declare.
Changed in version 3.7: preferred keyword-only parameter was added.


These functions expose the Windows registry API to Python. Instead of using an integer as the registry handle, a handle object is used to ensure that the handles are closed correctly, even if the programmer neglects to explicitly close them.
Changed in version 3.3: Several functions in this module used to raise a WindowsError, which is now an alias of OSError.
This module offers the following functions:
Closes a previously opened registry key. The hkey argument specifies a previously opened key.
Note
If hkey is not closed using this method (or via hkey.Close()), it is closed when the hkey object is destroyed by Python.
Establishes a connection to a predefined registry handle on another computer, and returns a handle object.
computer_name is the name of the remote computer, of the form r"\\computername". If None, the local computer is used.
key is the predefined handle to connect to.
The return value is the handle of the opened key. If the function fails, an OSError exception is raised.
Raises an auditing event winreg.ConnectRegistry with arguments computer_name, key.
Changed in version 3.3: See above.
Creates or opens the specified key, returning a handle object.
key is an already open key, or one of the predefined HKEY_* constants.
sub_key is a string that names the key this method opens or creates.
If key is one of the predefined keys, sub_key may be None. In that case, the handle returned is the same key handle passed in to the function.
If the key already exists, this function opens the existing key.
The return value is the handle of the opened key. If the function fails, an OSError exception is raised.
Raises an auditing event winreg.CreateKey with arguments key, sub_key, access.
Raises an auditing event winreg.OpenKey/result with argument key.
Changed in version 3.3: See above.
Creates or opens the specified key, returning a handle object.
key is an already open key, or one of the predefined HKEY_* constants.
sub_key is a string that names the key this method opens or creates.
reserved is a reserved integer, and must be zero. The default is zero.
access is an integer that specifies an access mask that describes the desired security access for the key. Default is KEY_WRITE. See Access Rights for other allowed values.
If key is one of the predefined keys, sub_key may be None. In that case, the handle returned is the same key handle passed in to the function.
If the key already exists, this function opens the existing key.
The return value is the handle of the opened key. If the function fails, an OSError exception is raised.
Raises an auditing event winreg.CreateKey with arguments key, sub_key, access.
Raises an auditing event winreg.OpenKey/result with argument key.
New in version 3.2.
Changed in version 3.3: See above.
Deletes the specified key.
key is an already open key, or one of the predefined HKEY_* constants.
sub_key is a string that must be a subkey of the key identified by the key parameter. This value must not be None, and the key may not have subkeys.
This method can not delete keys with subkeys.
If the method succeeds, the entire key, including all of its values, is removed. If the method fails, an OSError exception is raised.
Raises an auditing event winreg.DeleteKey with arguments key, sub_key, access.
Changed in version 3.3: See above.
Deletes the specified key.
Note
The DeleteKeyEx() function is implemented with the RegDeleteKeyEx Windows API function, which is specific to 64-bit versions of Windows. See the RegDeleteKeyEx documentation.
key is an already open key, or one of the predefined HKEY_* constants.
sub_key is a string that must be a subkey of the key identified by the key parameter. This value must not be None, and the key may not have subkeys.
reserved is a reserved integer, and must be zero. The default is zero.
access is an integer that specifies an access mask that describes the desired security access for the key. Default is KEY_WOW64_64KEY. See Access Rights for other allowed values.
This method can not delete keys with subkeys.
If the method succeeds, the entire key, including all of its values, is removed. If the method fails, an OSError exception is raised.
On unsupported Windows versions, NotImplementedError is raised.
Raises an auditing event winreg.DeleteKey with arguments key, sub_key, access.
New in version 3.2.
Changed in version 3.3: See above.
Removes a named value from a registry key.
key is an already open key, or one of the predefined HKEY_* constants.
value is a string that identifies the value to remove.
Raises an auditing event winreg.DeleteValue with arguments key, value.
Enumerates subkeys of an open registry key, returning a string.
key is an already open key, or one of the predefined HKEY_* constants.
index is an integer that identifies the index of the key to retrieve.
The function retrieves the name of one subkey each time it is called. It is typically called repeatedly until an OSError exception is raised, indicating, no more values are available.
Raises an auditing event winreg.EnumKey with arguments key, index.
Changed in version 3.3: See above.
Enumerates values of an open registry key, returning a tuple.
key is an already open key, or one of the predefined HKEY_* constants.
index is an integer that identifies the index of the value to retrieve.
The function retrieves the name of one subkey each time it is called. It is typically called repeatedly, until an OSError exception is raised, indicating no more values.
The result is a tuple of 3 items:
Index
Meaning
0
A string that identifies the value name
1
An object that holds the value data, and whose type depends on the underlying registry type
2
An integer that identifies the type of the value data (see table in docs for SetValueEx())
Raises an auditing event winreg.EnumValue with arguments key, index.
Changed in version 3.3: See above.
Expands environment variable placeholders %NAME% in strings like REG_EXPAND_SZ:
Raises an auditing event winreg.ExpandEnvironmentStrings with argument str.
Writes all the attributes of a key to the registry.
key is an already open key, or one of the predefined HKEY_* constants.
It is not necessary to call FlushKey() to change a key. Registry changes are flushed to disk by the registry using its lazy flusher. Registry changes are also flushed to disk at system shutdown. Unlike CloseKey(), the FlushKey() method returns only when all the data has been written to the registry. An application should only call FlushKey() if it requires absolute certainty that registry changes are on disk.
Note
If you don’t know whether a FlushKey() call is required, it probably isn’t.
Creates a subkey under the specified key and stores registration information from a specified file into that subkey.
key is a handle returned by ConnectRegistry() or one of the constants HKEY_USERS or HKEY_LOCAL_MACHINE.
sub_key is a string that identifies the subkey to load.
file_name is the name of the file to load registry data from. This file must have been created with the SaveKey() function. Under the file allocation table (FAT) file system, the filename may not have an extension.
A call to LoadKey() fails if the calling process does not have the SE_RESTORE_PRIVILEGE privilege. Note that privileges are different from permissions – see the RegLoadKey documentation for more details.
If key is a handle returned by ConnectRegistry(), then the path specified in file_name is relative to the remote computer.
Raises an auditing event winreg.LoadKey with arguments key, sub_key, file_name.
Opens the specified key, returning a handle object.
key is an already open key, or one of the predefined HKEY_* constants.
sub_key is a string that identifies the sub_key to open.
reserved is a reserved integer, and must be zero. The default is zero.
access is an integer that specifies an access mask that describes the desired security access for the key. Default is KEY_READ. See Access Rights for other allowed values.
The result is a new handle to the specified key.
If the function fails, OSError is raised.
Raises an auditing event winreg.OpenKey with arguments key, sub_key, access.
Raises an auditing event winreg.OpenKey/result with argument key.
Changed in version 3.2: Allow the use of named arguments.
Changed in version 3.3: See above.
Returns information about a key, as a tuple.
key is an already open key, or one of the predefined HKEY_* constants.
The result is a tuple of 3 items:
Index
Meaning
0
An integer giving the number of sub keys this key has.
1
An integer giving the number of values this key has.
2
An integer giving when the key was last modified (if available) as 100’s of nanoseconds since Jan 1, 1601.
Raises an auditing event winreg.QueryInfoKey with argument key.
Retrieves the unnamed value for a key, as a string.
key is an already open key, or one of the predefined HKEY_* constants.
sub_key is a string that holds the name of the subkey with which the value is associated. If this parameter is None or empty, the function retrieves the value set by the SetValue() method for the key identified by key.
Values in the registry have name, type, and data components. This method retrieves the data for a key’s first value that has a NULL name. But the underlying API call doesn’t return the type, so always use QueryValueEx() if possible.
Raises an auditing event winreg.QueryValue with arguments key, sub_key, value_name.
Retrieves the type and data for a specified value name associated with an open registry key.
key is an already open key, or one of the predefined HKEY_* constants.
value_name is a string indicating the value to query.
The result is a tuple of 2 items:
Index
Meaning
0
The value of the registry item.
1
An integer giving the registry type for this value (see table in docs for SetValueEx())
Raises an auditing event winreg.QueryValue with arguments key, sub_key, value_name.
Saves the specified key, and all its subkeys to the specified file.
key is an already open key, or one of the predefined HKEY_* constants.
file_name is the name of the file to save registry data to. This file cannot already exist. If this filename includes an extension, it cannot be used on file allocation table (FAT) file systems by the LoadKey() method.
If key represents a key on a remote computer, the path described by file_name is relative to the remote computer. The caller of this method must possess the SeBackupPrivilege security privilege. Note that privileges are different than permissions – see the Conflicts Between User Rights and Permissions documentation for more details.
This function passes NULL for security_attributes to the API.
Raises an auditing event winreg.SaveKey with arguments key, file_name.
Associates a value with a specified key.
key is an already open key, or one of the predefined HKEY_* constants.
sub_key is a string that names the subkey with which the value is associated.
type is an integer that specifies the type of the data. Currently this must be REG_SZ, meaning only strings are supported. Use the SetValueEx() function for support for other data types.
value is a string that specifies the new value.
If the key specified by the sub_key parameter does not exist, the SetValue function creates it.
Value lengths are limited by available memory. Long values (more than 2048 bytes) should be stored as files with the filenames stored in the configuration registry. This helps the registry perform efficiently.
The key identified by the key parameter must have been opened with KEY_SET_VALUE access.
Raises an auditing event winreg.SetValue with arguments key, sub_key, type, value.
Stores data in the value field of an open registry key.
key is an already open key, or one of the predefined HKEY_* constants.
value_name is a string that names the subkey with which the value is associated.
reserved can be anything – zero is always passed to the API.
type is an integer that specifies the type of the data. See Value Types for the available types.
value is a string that specifies the new value.
This method can also set additional value and type information for the specified key. The key identified by the key parameter must have been opened with KEY_SET_VALUE access.
To open the key, use the CreateKey() or OpenKey() methods.
Value lengths are limited by available memory. Long values (more than 2048 bytes) should be stored as files with the filenames stored in the configuration registry. This helps the registry perform efficiently.
Raises an auditing event winreg.SetValue with arguments key, sub_key, type, value.
Disables registry reflection for 32-bit processes running on a 64-bit operating system.
key is an already open key, or one of the predefined HKEY_* constants.
Will generally raise NotImplementedError if executed on a 32-bit operating system.
If the key is not on the reflection list, the function succeeds but has no effect. Disabling reflection for a key does not affect reflection of any subkeys.
Raises an auditing event winreg.DisableReflectionKey with argument key.
Restores registry reflection for the specified disabled key.
key is an already open key, or one of the predefined HKEY_* constants.
Will generally raise NotImplementedError if executed on a 32-bit operating system.
Restoring reflection for a key does not affect reflection of any subkeys.
Raises an auditing event winreg.EnableReflectionKey with argument key.
Determines the reflection state for the specified key.
key is an already open key, or one of the predefined HKEY_* constants.
Returns True if reflection is disabled.
Will generally raise NotImplementedError if executed on a 32-bit operating system.
Raises an auditing event winreg.QueryReflectionKey with argument key.
The following constants are defined for use in many _winreg functions.
Registry entries subordinate to this key define types (or classes) of documents and the properties associated with those types. Shell and COM applications use the information stored under this key.
Registry entries subordinate to this key define the preferences of the current user. These preferences include the settings of environment variables, data about program groups, colors, printers, network connections, and application preferences.
Registry entries subordinate to this key define the physical state of the computer, including data about the bus type, system memory, and installed hardware and software.
Registry entries subordinate to this key define the default user configuration for new users on the local computer and the user configuration for the current user.
Registry entries subordinate to this key allow you to access performance data. The data is not actually stored in the registry; the registry functions cause the system to collect the data from its source.
Contains information about the current hardware profile of the local computer system.
This key is not used in versions of Windows after 98.
For more information, see Registry Key Security and Access.
Combines the STANDARD_RIGHTS_REQUIRED, KEY_QUERY_VALUE, KEY_SET_VALUE, KEY_CREATE_SUB_KEY, KEY_ENUMERATE_SUB_KEYS, KEY_NOTIFY, and KEY_CREATE_LINK access rights.
Combines the STANDARD_RIGHTS_WRITE, KEY_SET_VALUE, and KEY_CREATE_SUB_KEY access rights.
Combines the STANDARD_RIGHTS_READ, KEY_QUERY_VALUE, KEY_ENUMERATE_SUB_KEYS, and KEY_NOTIFY values.
Equivalent to KEY_READ.
Required to query the values of a registry key.
Required to create, delete, or set a registry value.
Required to create a subkey of a registry key.
Required to enumerate the subkeys of a registry key.
Required to request change notifications for a registry key or for subkeys of a registry key.
Reserved for system use.
For more information, see Accessing an Alternate Registry View.
Indicates that an application on 64-bit Windows should operate on the 64-bit registry view.
Indicates that an application on 64-bit Windows should operate on the 32-bit registry view.
For more information, see Registry Value Types.
Binary data in any form.
32-bit number.
A 32-bit number in little-endian format. Equivalent to REG_DWORD.
A 32-bit number in big-endian format.
Null-terminated string containing references to environment variables (%PATH%).
A Unicode symbolic link.
A sequence of null-terminated strings, terminated by two null characters. (Python handles this termination automatically.)
No defined value type.
A 64-bit number.
New in version 3.6.
A 64-bit number in little-endian format. Equivalent to REG_QWORD.
New in version 3.6.
A device-driver resource list.
A hardware setting.
A hardware resource list.
A null-terminated string.
This object wraps a Windows HKEY object, automatically closing it when the object is destroyed. To guarantee cleanup, you can call either the Close() method on the object, or the CloseKey() function.
All registry functions in this module return one of these objects.
All registry functions in this module which accept a handle object also accept an integer, however, use of the handle object is encouraged.
Handle objects provide semantics for __bool__() – thus
will print Yes if the handle is currently valid (has not been closed or detached).
The object also support comparison semantics, so handle objects will compare true if they both reference the same underlying Windows handle value.
Handle objects can be converted to an integer (e.g., using the built-in int() function), in which case the underlying Windows handle value is returned. You can also use the Detach() method to return the integer handle, and also disconnect the Windows handle from the handle object.
Closes the underlying Windows handle.
If the handle is already closed, no error is raised.
Detaches the Windows handle from the handle object.
The result is an integer that holds the value of the handle before it is detached. If the handle is already detached or closed, this will return zero.
After calling this function, the handle is effectively invalidated, but the handle is not closed. You would call this function when you need the underlying Win32 handle to exist beyond the lifetime of the handle object.
Raises an auditing event winreg.PyHKEY.Detach with argument key.
The HKEY object implements __enter__() and __exit__() and thus supports the context protocol for the with statement:
will automatically close key when control leaves the with block.


Closes a previously opened registry key. The hkey argument specifies a previously opened key.
Note
If hkey is not closed using this method (or via hkey.Close()), it is closed when the hkey object is destroyed by Python.


Establishes a connection to a predefined registry handle on another computer, and returns a handle object.
computer_name is the name of the remote computer, of the form r"\\computername". If None, the local computer is used.
key is the predefined handle to connect to.
The return value is the handle of the opened key. If the function fails, an OSError exception is raised.
Raises an auditing event winreg.ConnectRegistry with arguments computer_name, key.
Changed in version 3.3: See above.


Creates or opens the specified key, returning a handle object.
key is an already open key, or one of the predefined HKEY_* constants.
sub_key is a string that names the key this method opens or creates.
If key is one of the predefined keys, sub_key may be None. In that case, the handle returned is the same key handle passed in to the function.
If the key already exists, this function opens the existing key.
The return value is the handle of the opened key. If the function fails, an OSError exception is raised.
Raises an auditing event winreg.CreateKey with arguments key, sub_key, access.
Raises an auditing event winreg.OpenKey/result with argument key.
Changed in version 3.3: See above.


Creates or opens the specified key, returning a handle object.
key is an already open key, or one of the predefined HKEY_* constants.
sub_key is a string that names the key this method opens or creates.
reserved is a reserved integer, and must be zero. The default is zero.
access is an integer that specifies an access mask that describes the desired security access for the key. Default is KEY_WRITE. See Access Rights for other allowed values.
If key is one of the predefined keys, sub_key may be None. In that case, the handle returned is the same key handle passed in to the function.
If the key already exists, this function opens the existing key.
The return value is the handle of the opened key. If the function fails, an OSError exception is raised.
Raises an auditing event winreg.CreateKey with arguments key, sub_key, access.
Raises an auditing event winreg.OpenKey/result with argument key.
New in version 3.2.
Changed in version 3.3: See above.


Deletes the specified key.
key is an already open key, or one of the predefined HKEY_* constants.
sub_key is a string that must be a subkey of the key identified by the key parameter. This value must not be None, and the key may not have subkeys.
This method can not delete keys with subkeys.
If the method succeeds, the entire key, including all of its values, is removed. If the method fails, an OSError exception is raised.
Raises an auditing event winreg.DeleteKey with arguments key, sub_key, access.
Changed in version 3.3: See above.


Deletes the specified key.
Note
The DeleteKeyEx() function is implemented with the RegDeleteKeyEx Windows API function, which is specific to 64-bit versions of Windows. See the RegDeleteKeyEx documentation.
key is an already open key, or one of the predefined HKEY_* constants.
sub_key is a string that must be a subkey of the key identified by the key parameter. This value must not be None, and the key may not have subkeys.
reserved is a reserved integer, and must be zero. The default is zero.
access is an integer that specifies an access mask that describes the desired security access for the key. Default is KEY_WOW64_64KEY. See Access Rights for other allowed values.
This method can not delete keys with subkeys.
If the method succeeds, the entire key, including all of its values, is removed. If the method fails, an OSError exception is raised.
On unsupported Windows versions, NotImplementedError is raised.
Raises an auditing event winreg.DeleteKey with arguments key, sub_key, access.
New in version 3.2.
Changed in version 3.3: See above.


Removes a named value from a registry key.
key is an already open key, or one of the predefined HKEY_* constants.
value is a string that identifies the value to remove.
Raises an auditing event winreg.DeleteValue with arguments key, value.


Disables registry reflection for 32-bit processes running on a 64-bit operating system.
key is an already open key, or one of the predefined HKEY_* constants.
Will generally raise NotImplementedError if executed on a 32-bit operating system.
If the key is not on the reflection list, the function succeeds but has no effect. Disabling reflection for a key does not affect reflection of any subkeys.
Raises an auditing event winreg.DisableReflectionKey with argument key.


Restores registry reflection for the specified disabled key.
key is an already open key, or one of the predefined HKEY_* constants.
Will generally raise NotImplementedError if executed on a 32-bit operating system.
Restoring reflection for a key does not affect reflection of any subkeys.
Raises an auditing event winreg.EnableReflectionKey with argument key.


Enumerates subkeys of an open registry key, returning a string.
key is an already open key, or one of the predefined HKEY_* constants.
index is an integer that identifies the index of the key to retrieve.
The function retrieves the name of one subkey each time it is called. It is typically called repeatedly until an OSError exception is raised, indicating, no more values are available.
Raises an auditing event winreg.EnumKey with arguments key, index.
Changed in version 3.3: See above.


Enumerates values of an open registry key, returning a tuple.
key is an already open key, or one of the predefined HKEY_* constants.
index is an integer that identifies the index of the value to retrieve.
The function retrieves the name of one subkey each time it is called. It is typically called repeatedly, until an OSError exception is raised, indicating no more values.
The result is a tuple of 3 items:
Index
Meaning
0
A string that identifies the value name
1
An object that holds the value data, and whose type depends on the underlying registry type
2
An integer that identifies the type of the value data (see table in docs for SetValueEx())
Raises an auditing event winreg.EnumValue with arguments key, index.
Changed in version 3.3: See above.


Expands environment variable placeholders %NAME% in strings like REG_EXPAND_SZ:
Raises an auditing event winreg.ExpandEnvironmentStrings with argument str.


Writes all the attributes of a key to the registry.
key is an already open key, or one of the predefined HKEY_* constants.
It is not necessary to call FlushKey() to change a key. Registry changes are flushed to disk by the registry using its lazy flusher. Registry changes are also flushed to disk at system shutdown. Unlike CloseKey(), the FlushKey() method returns only when all the data has been written to the registry. An application should only call FlushKey() if it requires absolute certainty that registry changes are on disk.
Note
If you don’t know whether a FlushKey() call is required, it probably isn’t.


Registry entries subordinate to this key define types (or classes) of documents and the properties associated with those types. Shell and COM applications use the information stored under this key.


Contains information about the current hardware profile of the local computer system.


Registry entries subordinate to this key define the preferences of the current user. These preferences include the settings of environment variables, data about program groups, colors, printers, network connections, and application preferences.


This key is not used in versions of Windows after 98.


Registry entries subordinate to this key define the physical state of the computer, including data about the bus type, system memory, and installed hardware and software.


Registry entries subordinate to this key allow you to access performance data. The data is not actually stored in the registry; the registry functions cause the system to collect the data from its source.


Registry entries subordinate to this key define the default user configuration for new users on the local computer and the user configuration for the current user.


Combines the STANDARD_RIGHTS_REQUIRED, KEY_QUERY_VALUE, KEY_SET_VALUE, KEY_CREATE_SUB_KEY, KEY_ENUMERATE_SUB_KEYS, KEY_NOTIFY, and KEY_CREATE_LINK access rights.


Required to create a subkey of a registry key.


Required to enumerate the subkeys of a registry key.


Required to request change notifications for a registry key or for subkeys of a registry key.


Required to query the values of a registry key.


Combines the STANDARD_RIGHTS_READ, KEY_QUERY_VALUE, KEY_ENUMERATE_SUB_KEYS, and KEY_NOTIFY values.


Required to create, delete, or set a registry value.


Indicates that an application on 64-bit Windows should operate on the 32-bit registry view.


Indicates that an application on 64-bit Windows should operate on the 64-bit registry view.


Combines the STANDARD_RIGHTS_WRITE, KEY_SET_VALUE, and KEY_CREATE_SUB_KEY access rights.


Creates a subkey under the specified key and stores registration information from a specified file into that subkey.
key is a handle returned by ConnectRegistry() or one of the constants HKEY_USERS or HKEY_LOCAL_MACHINE.
sub_key is a string that identifies the subkey to load.
file_name is the name of the file to load registry data from. This file must have been created with the SaveKey() function. Under the file allocation table (FAT) file system, the filename may not have an extension.
A call to LoadKey() fails if the calling process does not have the SE_RESTORE_PRIVILEGE privilege. Note that privileges are different from permissions – see the RegLoadKey documentation for more details.
If key is a handle returned by ConnectRegistry(), then the path specified in file_name is relative to the remote computer.
Raises an auditing event winreg.LoadKey with arguments key, sub_key, file_name.