doc_content stringlengths 1 386k | doc_id stringlengths 5 188 |
|---|---|
setup_scripts(context)
Installs activation scripts appropriate to the platform into the virtual environment. | python.library.venv#venv.EnvBuilder.setup_scripts |
upgrade_dependencies(context)
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. | python.library.venv#venv.EnvBuilder.upgrade_dependencies |
exception Warning
Base class for warning categories. | python.library.exceptions#Warning |
warnings — Warning control 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. Warning Categories 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 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
message is a string containing a regular expression that the start of the warning message must match. The expression is compiled to always be case-insensitive.
category is a class (a subclass of Warning) of which the warning category must be a subclass in order to match.
module is a string containing a regular expression that the module name must match. The expression is compiled to be case-sensitive.
lineno is an integer that the line number where the warning occurred must match, or 0 to match all line numbers. 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). Describing Warning Filters 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: action:message:category:module:line
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: default # Show all warnings (even those ignored by default)
ignore # Ignore all warnings
error # Convert all warnings to errors
error::ResourceWarning # Treat ResourceWarning messages as errors
default::DeprecationWarning # Show DeprecationWarning messages
ignore,default:::mymodule # Only report warnings triggered by "mymodule"
error:::mymodule[.*] # Convert warnings to errors in "mymodule"
# and any subpackages of "mymodule"
Default Warning Filter 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): default::DeprecationWarning:__main__
ignore::DeprecationWarning
ignore::PendingDeprecationWarning
ignore::ImportWarning
ignore::ResourceWarning
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. Overriding the default filter 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: import sys
if not sys.warnoptions:
import warnings
warnings.simplefilter("ignore")
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: import sys
if not sys.warnoptions:
import os, warnings
warnings.simplefilter("default") # Change the filter in this process
os.environ["PYTHONWARNINGS"] = "default" # Also affect subprocesses
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): import warnings
warnings.filterwarnings("default", category=DeprecationWarning,
module=user_ns.get("__name__"))
Temporarily Suppressing Warnings 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: import warnings
def fxn():
warnings.warn("deprecated", DeprecationWarning)
with warnings.catch_warnings():
warnings.simplefilter("ignore")
fxn()
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. Testing Warnings 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: import warnings
def fxn():
warnings.warn("deprecated", DeprecationWarning)
with warnings.catch_warnings(record=True) as w:
# Cause all warnings to always be triggered.
warnings.simplefilter("always")
# Trigger a warning.
fxn()
# Verify some things
assert len(w) == 1
assert issubclass(w[-1].category, DeprecationWarning)
assert "deprecated" in str(w[-1].message)
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). Updating Code For New Versions of Dependencies 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. Available Functions
warnings.warn(message, category=None, stacklevel=1, source=None)
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: def deprecation(message):
warnings.warn(message, DeprecationWarning, stacklevel=2)
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.
warnings.warn_explicit(message, category, filename, lineno, module=None, registry=None, module_globals=None, source=None)
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.
warnings.showwarning(message, category, filename, lineno, file=None, line=None)
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.
warnings.formatwarning(message, category, filename, lineno, line=None)
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.
warnings.filterwarnings(action, message='', category=Warning, module='', lineno=0, append=False)
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.
warnings.simplefilter(action, category=Warning, lineno=0, append=False)
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.
warnings.resetwarnings()
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().
Available Context Managers
class warnings.catch_warnings(*, record=False, module=None)
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. | python.library.warnings |
class warnings.catch_warnings(*, record=False, module=None)
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. | python.library.warnings#warnings.catch_warnings |
warnings.filterwarnings(action, message='', category=Warning, module='', lineno=0, append=False)
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. | python.library.warnings#warnings.filterwarnings |
warnings.formatwarning(message, category, filename, lineno, line=None)
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. | python.library.warnings#warnings.formatwarning |
warnings.resetwarnings()
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(). | python.library.warnings#warnings.resetwarnings |
warnings.showwarning(message, category, filename, lineno, file=None, line=None)
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. | python.library.warnings#warnings.showwarning |
warnings.simplefilter(action, category=Warning, lineno=0, append=False)
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. | python.library.warnings#warnings.simplefilter |
warnings.warn(message, category=None, stacklevel=1, source=None)
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: def deprecation(message):
warnings.warn(message, DeprecationWarning, stacklevel=2)
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. | python.library.warnings#warnings.warn |
warnings.warn_explicit(message, category, filename, lineno, module=None, registry=None, module_globals=None, source=None)
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. | python.library.warnings#warnings.warn_explicit |
wave — Read and write WAV files 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:
wave.open(file, mode=None)
If file is a string, open the file by that name, otherwise treat it as a file-like object. mode can be:
'rb'
Read only mode.
'wb'
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.
exception wave.Error
An error raised when something is impossible because it violates the WAV specification or hits an implementation deficiency.
Wave_read Objects Wave_read objects, as returned by open(), have the following methods:
Wave_read.close()
Close the stream if it was opened by wave, and make the instance unusable. This is called automatically on object collection.
Wave_read.getnchannels()
Returns number of audio channels (1 for mono, 2 for stereo).
Wave_read.getsampwidth()
Returns sample width in bytes.
Wave_read.getframerate()
Returns sampling frequency.
Wave_read.getnframes()
Returns number of audio frames.
Wave_read.getcomptype()
Returns compression type ('NONE' is the only supported type).
Wave_read.getcompname()
Human-readable version of getcomptype(). Usually 'not compressed' parallels 'NONE'.
Wave_read.getparams()
Returns a namedtuple() (nchannels, sampwidth,
framerate, nframes, comptype, compname), equivalent to output of the get*() methods.
Wave_read.readframes(n)
Reads and returns at most n frames of audio, as a bytes object.
Wave_read.rewind()
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.
Wave_read.getmarkers()
Returns None.
Wave_read.getmark(id)
Raise an error.
The following two methods define a term “position” which is compatible between them, and is otherwise implementation dependent.
Wave_read.setpos(pos)
Set the file pointer to the specified position.
Wave_read.tell()
Return current file pointer position.
Wave_write Objects 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.
Wave_write.close()
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.
Wave_write.setnchannels(n)
Set the number of channels.
Wave_write.setsampwidth(n)
Set the sample width to n bytes.
Wave_write.setframerate(n)
Set the frame rate to n. Changed in version 3.2: A non-integral input to this method is rounded to the nearest integer.
Wave_write.setnframes(n)
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).
Wave_write.setcomptype(type, name)
Set the compression type and description. At the moment, only compression type NONE is supported, meaning no compression.
Wave_write.setparams(tuple)
The tuple should be (nchannels, sampwidth, framerate, nframes, comptype,
compname), with values valid for the set*() methods. Sets all parameters.
Wave_write.tell()
Return current position in the file, with the same disclaimer for the Wave_read.tell() and Wave_read.setpos() methods.
Wave_write.writeframesraw(data)
Write audio frames, without correcting nframes. Changed in version 3.4: Any bytes-like object is now accepted.
Wave_write.writeframes(data)
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. | python.library.wave |
exception wave.Error
An error raised when something is impossible because it violates the WAV specification or hits an implementation deficiency. | python.library.wave#wave.Error |
wave.open(file, mode=None)
If file is a string, open the file by that name, otherwise treat it as a file-like object. mode can be:
'rb'
Read only mode.
'wb'
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. | python.library.wave#wave.open |
Wave_read.close()
Close the stream if it was opened by wave, and make the instance unusable. This is called automatically on object collection. | python.library.wave#wave.Wave_read.close |
Wave_read.getcompname()
Human-readable version of getcomptype(). Usually 'not compressed' parallels 'NONE'. | python.library.wave#wave.Wave_read.getcompname |
Wave_read.getcomptype()
Returns compression type ('NONE' is the only supported type). | python.library.wave#wave.Wave_read.getcomptype |
Wave_read.getframerate()
Returns sampling frequency. | python.library.wave#wave.Wave_read.getframerate |
Wave_read.getmark(id)
Raise an error. | python.library.wave#wave.Wave_read.getmark |
Wave_read.getmarkers()
Returns None. | python.library.wave#wave.Wave_read.getmarkers |
Wave_read.getnchannels()
Returns number of audio channels (1 for mono, 2 for stereo). | python.library.wave#wave.Wave_read.getnchannels |
Wave_read.getnframes()
Returns number of audio frames. | python.library.wave#wave.Wave_read.getnframes |
Wave_read.getparams()
Returns a namedtuple() (nchannels, sampwidth,
framerate, nframes, comptype, compname), equivalent to output of the get*() methods. | python.library.wave#wave.Wave_read.getparams |
Wave_read.getsampwidth()
Returns sample width in bytes. | python.library.wave#wave.Wave_read.getsampwidth |
Wave_read.readframes(n)
Reads and returns at most n frames of audio, as a bytes object. | python.library.wave#wave.Wave_read.readframes |
Wave_read.rewind()
Rewind the file pointer to the beginning of the audio stream. | python.library.wave#wave.Wave_read.rewind |
Wave_read.setpos(pos)
Set the file pointer to the specified position. | python.library.wave#wave.Wave_read.setpos |
Wave_read.tell()
Return current file pointer position. | python.library.wave#wave.Wave_read.tell |
Wave_write.close()
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. | python.library.wave#wave.Wave_write.close |
Wave_write.setcomptype(type, name)
Set the compression type and description. At the moment, only compression type NONE is supported, meaning no compression. | python.library.wave#wave.Wave_write.setcomptype |
Wave_write.setframerate(n)
Set the frame rate to n. Changed in version 3.2: A non-integral input to this method is rounded to the nearest integer. | python.library.wave#wave.Wave_write.setframerate |
Wave_write.setnchannels(n)
Set the number of channels. | python.library.wave#wave.Wave_write.setnchannels |
Wave_write.setnframes(n)
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). | python.library.wave#wave.Wave_write.setnframes |
Wave_write.setparams(tuple)
The tuple should be (nchannels, sampwidth, framerate, nframes, comptype,
compname), with values valid for the set*() methods. Sets all parameters. | python.library.wave#wave.Wave_write.setparams |
Wave_write.setsampwidth(n)
Set the sample width to n bytes. | python.library.wave#wave.Wave_write.setsampwidth |
Wave_write.tell()
Return current position in the file, with the same disclaimer for the Wave_read.tell() and Wave_read.setpos() methods. | python.library.wave#wave.Wave_write.tell |
Wave_write.writeframes(data)
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. | python.library.wave#wave.Wave_write.writeframes |
Wave_write.writeframesraw(data)
Write audio frames, without correcting nframes. Changed in version 3.4: Any bytes-like object is now accepted. | python.library.wave#wave.Wave_write.writeframesraw |
weakref — Weak references 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: class Dict(dict):
pass
obj = Dict(red=1, green=2, blue=3) # this object is weak referenceable
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.
class weakref.ref(object[, callback])
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.
__callback__
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.
weakref.proxy(object[, callback])
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 @=.
weakref.getweakrefcount(object)
Return the number of weak references and proxies which refer to object.
weakref.getweakrefs(object)
Return a list of all weak reference and proxy objects which refer to object.
class weakref.WeakKeyDictionary([dict])
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.
WeakKeyDictionary.keyrefs()
Return an iterable of the weak references to the keys.
class weakref.WeakValueDictionary([dict])
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.
WeakValueDictionary.valuerefs()
Return an iterable of the weak references to the values.
class weakref.WeakSet([elements])
Set class that keeps weak references to its elements. An element will be discarded when no strong reference to it exists any more.
class weakref.WeakMethod(method)
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: >>> class C:
... def method(self):
... print("method called!")
...
>>> c = C()
>>> r = weakref.ref(c.method)
>>> r()
>>> r = weakref.WeakMethod(c.method)
>>> r()
<bound method C.method of <__main__.C object at 0x7fc859830220>>
>>> r()()
method called!
>>> del c
>>> gc.collect()
0
>>> r()
>>>
New in version 3.4.
class weakref.finalize(obj, func, /, *args, **kwargs)
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.
__call__()
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.
detach()
If self is alive then mark it as dead and return the tuple (obj, func, args, kwargs). If self is dead then return None.
peek()
If self is alive then return the tuple (obj, func, args,
kwargs). If self is dead then return None.
alive
Property which is true if the finalizer is alive, false otherwise.
atexit
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.
weakref.ReferenceType
The type object for weak references objects.
weakref.ProxyType
The type object for proxies of objects which are not callable.
weakref.CallableProxyType
The type object for proxies of callable objects.
weakref.ProxyTypes
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
PEP 205 - Weak References
The proposal and rationale for this feature, including links to earlier implementations and information about similar features in other languages. Weak Reference Objects 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: >>> import weakref
>>> class Object:
... pass
...
>>> o = Object()
>>> r = weakref.ref(o)
>>> o2 = r()
>>> o is o2
True
If the referent no longer exists, calling the reference object returns None: >>> del o, o2
>>> print(r())
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: # r is a weak reference object
o = r()
if o is None:
# referent has been garbage collected
print("Object has been deallocated; can't frobnicate.")
else:
print("Object is still live!")
o.do_something_useful()
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: import weakref
class ExtendedRef(weakref.ref):
def __init__(self, ob, callback=None, /, **annotations):
super().__init__(ob, callback)
self.__counter = 0
for k, v in annotations.items():
setattr(self, k, v)
def __call__(self):
"""Return a pair containing the referent and the number of
times the reference has been called.
"""
ob = super().__call__()
if ob is not None:
self.__counter += 1
ob = (ob, self.__counter)
return ob
Example 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. import weakref
_id2obj_dict = weakref.WeakValueDictionary()
def remember(obj):
oid = id(obj)
_id2obj_dict[oid] = obj
return oid
def id2obj(oid):
return _id2obj_dict[oid]
Finalizer Objects 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 >>> import weakref
>>> class Object:
... pass
...
>>> kenny = Object()
>>> weakref.finalize(kenny, print, "You killed Kenny!")
<finalize object at ...; for 'Object' at ...>
>>> del kenny
You killed Kenny!
The finalizer can be called directly as well. However the finalizer will invoke the callback at most once. >>> def callback(x, y, z):
... print("CALLBACK")
... return x + y + z
...
>>> obj = Object()
>>> f = weakref.finalize(obj, callback, 1, 2, z=3)
>>> assert f.alive
>>> assert f() == 6
CALLBACK
>>> assert not f.alive
>>> f() # callback not called because finalizer dead
>>> del obj # callback not called because finalizer dead
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. >>> obj = Object()
>>> f = weakref.finalize(obj, callback, 1, 2, z=3)
>>> f.detach()
(<...Object object ...>, <function callback ...>, (1, 2), {'z': 3})
>>> newobj, func, args, kwargs = _
>>> assert not f.alive
>>> assert newobj is obj
>>> assert func(*args, **kwargs) == 6
CALLBACK
Unless you set the atexit attribute to False, a finalizer will be called when the program exits if it is still alive. For instance >>> obj = Object()
>>> weakref.finalize(obj, print, "obj dead or exiting")
<finalize object at ...; for 'Object' at ...>
>>> exit()
obj dead or exiting
Comparing finalizers with __del__() methods 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: the object is garbage collected, the object’s remove() method is called, or the program exits. We might try to implement the class using a __del__() method as follows: class TempDir:
def __init__(self):
self.name = tempfile.mkdtemp()
def remove(self):
if self.name is not None:
shutil.rmtree(self.name)
self.name = None
@property
def removed(self):
return self.name is None
def __del__(self):
self.remove()
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: class TempDir:
def __init__(self):
self.name = tempfile.mkdtemp()
self._finalizer = weakref.finalize(self, shutil.rmtree, self.name)
def remove(self):
self._finalizer()
@property
def removed(self):
return not self._finalizer.alive
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: import weakref, sys
def unloading_module():
# implicit reference to the module globals from the function body
weakref.finalize(sys.modules[__name__], unloading_module)
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. | python.library.weakref |
weakref.CallableProxyType
The type object for proxies of callable objects. | python.library.weakref#weakref.CallableProxyType |
class weakref.finalize(obj, func, /, *args, **kwargs)
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.
__call__()
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.
detach()
If self is alive then mark it as dead and return the tuple (obj, func, args, kwargs). If self is dead then return None.
peek()
If self is alive then return the tuple (obj, func, args,
kwargs). If self is dead then return None.
alive
Property which is true if the finalizer is alive, false otherwise.
atexit
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. | python.library.weakref#weakref.finalize |
alive
Property which is true if the finalizer is alive, false otherwise. | python.library.weakref#weakref.finalize.alive |
atexit
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. | python.library.weakref#weakref.finalize.atexit |
detach()
If self is alive then mark it as dead and return the tuple (obj, func, args, kwargs). If self is dead then return None. | python.library.weakref#weakref.finalize.detach |
peek()
If self is alive then return the tuple (obj, func, args,
kwargs). If self is dead then return None. | python.library.weakref#weakref.finalize.peek |
__call__()
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. | python.library.weakref#weakref.finalize.__call__ |
weakref.getweakrefcount(object)
Return the number of weak references and proxies which refer to object. | python.library.weakref#weakref.getweakrefcount |
weakref.getweakrefs(object)
Return a list of all weak reference and proxy objects which refer to object. | python.library.weakref#weakref.getweakrefs |
weakref.proxy(object[, callback])
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 @=. | python.library.weakref#weakref.proxy |
weakref.ProxyType
The type object for proxies of objects which are not callable. | python.library.weakref#weakref.ProxyType |
weakref.ProxyTypes
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. | python.library.weakref#weakref.ProxyTypes |
class weakref.ref(object[, callback])
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.
__callback__
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. | python.library.weakref#weakref.ref |
__callback__
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. | python.library.weakref#weakref.ref.__callback__ |
weakref.ReferenceType
The type object for weak references objects. | python.library.weakref#weakref.ReferenceType |
class weakref.WeakKeyDictionary([dict])
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. | python.library.weakref#weakref.WeakKeyDictionary |
WeakKeyDictionary.keyrefs()
Return an iterable of the weak references to the keys. | python.library.weakref#weakref.WeakKeyDictionary.keyrefs |
class weakref.WeakMethod(method)
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: >>> class C:
... def method(self):
... print("method called!")
...
>>> c = C()
>>> r = weakref.ref(c.method)
>>> r()
>>> r = weakref.WeakMethod(c.method)
>>> r()
<bound method C.method of <__main__.C object at 0x7fc859830220>>
>>> r()()
method called!
>>> del c
>>> gc.collect()
0
>>> r()
>>>
New in version 3.4. | python.library.weakref#weakref.WeakMethod |
class weakref.WeakSet([elements])
Set class that keeps weak references to its elements. An element will be discarded when no strong reference to it exists any more. | python.library.weakref#weakref.WeakSet |
class weakref.WeakValueDictionary([dict])
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. | python.library.weakref#weakref.WeakValueDictionary |
WeakValueDictionary.valuerefs()
Return an iterable of the weak references to the values. | python.library.weakref#weakref.WeakValueDictionary.valuerefs |
webbrowser — Convenient Web-browser controller 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: python -m webbrowser -t "http://www.python.org"
The following exception is defined:
exception webbrowser.Error
Exception raised when a browser control error occurs.
The following functions are defined:
webbrowser.open(url, new=0, autoraise=True)
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.
webbrowser.open_new(url)
Open url in a new window of the default browser, if possible, otherwise, open url in the only browser window.
webbrowser.open_new_tab(url)
Open url in a new page (“tab”) of the default browser, if possible, otherwise equivalent to open_new().
webbrowser.get(using=None)
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.
webbrowser.register(name, constructor, instance=None, *, preferred=False)
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: “Konqueror” is the file manager for the KDE desktop environment for Unix, and only makes sense to use if KDE is running. Some way of reliably detecting KDE would be nice; the KDEDIR variable is not sufficient. Note also that the name “kfm” is used even when using the konqueror command with KDE 2 — the implementation selects the best strategy for running Konqueror. Only on Windows platforms. Only on Mac OS X platform. New in version 3.3: Support for Chrome/Chromium has been added. Here are some simple examples: url = 'http://docs.python.org/'
# Open URL in a new tab, if a browser window is already open.
webbrowser.open_new_tab(url)
# Open URL in new window, raising the window if possible.
webbrowser.open_new(url)
Browser Controller Objects Browser controllers provide these methods which parallel three of the module-level convenience functions:
controller.open(url, new=0, autoraise=True)
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.
controller.open_new(url)
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().
controller.open_new_tab(url)
Open url in a new page (“tab”) of the browser handled by this controller, if possible, otherwise equivalent to open_new().
Footnotes
1
Executables named here without a full path will be searched in the directories given in the PATH environment variable. | python.library.webbrowser |
controller.open(url, new=0, autoraise=True)
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. | python.library.webbrowser#webbrowser.controller.open |
controller.open_new(url)
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(). | python.library.webbrowser#webbrowser.controller.open_new |
controller.open_new_tab(url)
Open url in a new page (“tab”) of the browser handled by this controller, if possible, otherwise equivalent to open_new(). | python.library.webbrowser#webbrowser.controller.open_new_tab |
exception webbrowser.Error
Exception raised when a browser control error occurs. | python.library.webbrowser#webbrowser.Error |
webbrowser.get(using=None)
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. | python.library.webbrowser#webbrowser.get |
webbrowser.open(url, new=0, autoraise=True)
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. | python.library.webbrowser#webbrowser.open |
webbrowser.open_new(url)
Open url in a new window of the default browser, if possible, otherwise, open url in the only browser window. | python.library.webbrowser#webbrowser.open_new |
webbrowser.open_new_tab(url)
Open url in a new page (“tab”) of the default browser, if possible, otherwise equivalent to open_new(). | python.library.webbrowser#webbrowser.open_new_tab |
webbrowser.register(name, constructor, instance=None, *, preferred=False)
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. | python.library.webbrowser#webbrowser.register |
exception WindowsError
Only available on Windows. | python.library.exceptions#WindowsError |
winreg — Windows registry access 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. Functions This module offers the following functions:
winreg.CloseKey(hkey)
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.
winreg.ConnectRegistry(computer_name, key)
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.
winreg.CreateKey(key, sub_key)
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.
winreg.CreateKeyEx(key, sub_key, reserved=0, access=KEY_WRITE)
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.
winreg.DeleteKey(key, sub_key)
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.
winreg.DeleteKeyEx(key, sub_key, access=KEY_WOW64_64KEY, reserved=0)
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.
winreg.DeleteValue(key, value)
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.
winreg.EnumKey(key, index)
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.
winreg.EnumValue(key, index)
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.
winreg.ExpandEnvironmentStrings(str)
Expands environment variable placeholders %NAME% in strings like REG_EXPAND_SZ: >>> ExpandEnvironmentStrings('%windir%')
'C:\\Windows'
Raises an auditing event winreg.ExpandEnvironmentStrings with argument str.
winreg.FlushKey(key)
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.
winreg.LoadKey(key, sub_key, file_name)
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.
winreg.OpenKey(key, sub_key, reserved=0, access=KEY_READ)
winreg.OpenKeyEx(key, sub_key, reserved=0, access=KEY_READ)
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.
winreg.QueryInfoKey(key)
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.
winreg.QueryValue(key, sub_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.
winreg.QueryValueEx(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.
winreg.SaveKey(key, file_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.
winreg.SetValue(key, sub_key, type, value)
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.
winreg.SetValueEx(key, value_name, reserved, 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.
winreg.DisableReflectionKey(key)
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.
winreg.EnableReflectionKey(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.
winreg.QueryReflectionKey(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.
Constants The following constants are defined for use in many _winreg functions. HKEY_* Constants
winreg.HKEY_CLASSES_ROOT
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.
winreg.HKEY_CURRENT_USER
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.
winreg.HKEY_LOCAL_MACHINE
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.
winreg.HKEY_USERS
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.
winreg.HKEY_PERFORMANCE_DATA
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.
winreg.HKEY_CURRENT_CONFIG
Contains information about the current hardware profile of the local computer system.
winreg.HKEY_DYN_DATA
This key is not used in versions of Windows after 98.
Access Rights For more information, see Registry Key Security and Access.
winreg.KEY_ALL_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.
winreg.KEY_WRITE
Combines the STANDARD_RIGHTS_WRITE, KEY_SET_VALUE, and KEY_CREATE_SUB_KEY access rights.
winreg.KEY_READ
Combines the STANDARD_RIGHTS_READ, KEY_QUERY_VALUE, KEY_ENUMERATE_SUB_KEYS, and KEY_NOTIFY values.
winreg.KEY_EXECUTE
Equivalent to KEY_READ.
winreg.KEY_QUERY_VALUE
Required to query the values of a registry key.
winreg.KEY_SET_VALUE
Required to create, delete, or set a registry value.
winreg.KEY_CREATE_SUB_KEY
Required to create a subkey of a registry key.
winreg.KEY_ENUMERATE_SUB_KEYS
Required to enumerate the subkeys of a registry key.
winreg.KEY_NOTIFY
Required to request change notifications for a registry key or for subkeys of a registry key.
winreg.KEY_CREATE_LINK
Reserved for system use.
64-bit Specific For more information, see Accessing an Alternate Registry View.
winreg.KEY_WOW64_64KEY
Indicates that an application on 64-bit Windows should operate on the 64-bit registry view.
winreg.KEY_WOW64_32KEY
Indicates that an application on 64-bit Windows should operate on the 32-bit registry view.
Value Types For more information, see Registry Value Types.
winreg.REG_BINARY
Binary data in any form.
winreg.REG_DWORD
32-bit number.
winreg.REG_DWORD_LITTLE_ENDIAN
A 32-bit number in little-endian format. Equivalent to REG_DWORD.
winreg.REG_DWORD_BIG_ENDIAN
A 32-bit number in big-endian format.
winreg.REG_EXPAND_SZ
Null-terminated string containing references to environment variables (%PATH%).
winreg.REG_LINK
A Unicode symbolic link.
winreg.REG_MULTI_SZ
A sequence of null-terminated strings, terminated by two null characters. (Python handles this termination automatically.)
winreg.REG_NONE
No defined value type.
winreg.REG_QWORD
A 64-bit number. New in version 3.6.
winreg.REG_QWORD_LITTLE_ENDIAN
A 64-bit number in little-endian format. Equivalent to REG_QWORD. New in version 3.6.
winreg.REG_RESOURCE_LIST
A device-driver resource list.
winreg.REG_FULL_RESOURCE_DESCRIPTOR
A hardware setting.
winreg.REG_RESOURCE_REQUIREMENTS_LIST
A hardware resource list.
winreg.REG_SZ
A null-terminated string.
Registry Handle Objects 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 if handle:
print("Yes")
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.
PyHKEY.Close()
Closes the underlying Windows handle. If the handle is already closed, no error is raised.
PyHKEY.Detach()
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.
PyHKEY.__enter__()
PyHKEY.__exit__(*exc_info)
The HKEY object implements __enter__() and __exit__() and thus supports the context protocol for the with statement: with OpenKey(HKEY_LOCAL_MACHINE, "foo") as key:
... # work with key
will automatically close key when control leaves the with block. | python.library.winreg |
winreg.CloseKey(hkey)
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. | python.library.winreg#winreg.CloseKey |
winreg.ConnectRegistry(computer_name, key)
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. | python.library.winreg#winreg.ConnectRegistry |
winreg.CreateKey(key, sub_key)
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. | python.library.winreg#winreg.CreateKey |
winreg.CreateKeyEx(key, sub_key, reserved=0, access=KEY_WRITE)
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. | python.library.winreg#winreg.CreateKeyEx |
winreg.DeleteKey(key, sub_key)
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. | python.library.winreg#winreg.DeleteKey |
winreg.DeleteKeyEx(key, sub_key, access=KEY_WOW64_64KEY, reserved=0)
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. | python.library.winreg#winreg.DeleteKeyEx |
winreg.DeleteValue(key, value)
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. | python.library.winreg#winreg.DeleteValue |
winreg.DisableReflectionKey(key)
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. | python.library.winreg#winreg.DisableReflectionKey |
winreg.EnableReflectionKey(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. | python.library.winreg#winreg.EnableReflectionKey |
winreg.EnumKey(key, index)
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. | python.library.winreg#winreg.EnumKey |
winreg.EnumValue(key, index)
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. | python.library.winreg#winreg.EnumValue |
winreg.ExpandEnvironmentStrings(str)
Expands environment variable placeholders %NAME% in strings like REG_EXPAND_SZ: >>> ExpandEnvironmentStrings('%windir%')
'C:\\Windows'
Raises an auditing event winreg.ExpandEnvironmentStrings with argument str. | python.library.winreg#winreg.ExpandEnvironmentStrings |
winreg.FlushKey(key)
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. | python.library.winreg#winreg.FlushKey |
winreg.HKEY_CLASSES_ROOT
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. | python.library.winreg#winreg.HKEY_CLASSES_ROOT |
winreg.HKEY_CURRENT_CONFIG
Contains information about the current hardware profile of the local computer system. | python.library.winreg#winreg.HKEY_CURRENT_CONFIG |
winreg.HKEY_CURRENT_USER
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. | python.library.winreg#winreg.HKEY_CURRENT_USER |
winreg.HKEY_DYN_DATA
This key is not used in versions of Windows after 98. | python.library.winreg#winreg.HKEY_DYN_DATA |
winreg.HKEY_LOCAL_MACHINE
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. | python.library.winreg#winreg.HKEY_LOCAL_MACHINE |
winreg.HKEY_PERFORMANCE_DATA
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. | python.library.winreg#winreg.HKEY_PERFORMANCE_DATA |
winreg.HKEY_USERS
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. | python.library.winreg#winreg.HKEY_USERS |
winreg.KEY_ALL_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. | python.library.winreg#winreg.KEY_ALL_ACCESS |
winreg.KEY_CREATE_LINK
Reserved for system use. | python.library.winreg#winreg.KEY_CREATE_LINK |
winreg.KEY_CREATE_SUB_KEY
Required to create a subkey of a registry key. | python.library.winreg#winreg.KEY_CREATE_SUB_KEY |
winreg.KEY_ENUMERATE_SUB_KEYS
Required to enumerate the subkeys of a registry key. | python.library.winreg#winreg.KEY_ENUMERATE_SUB_KEYS |
winreg.KEY_EXECUTE
Equivalent to KEY_READ. | python.library.winreg#winreg.KEY_EXECUTE |
winreg.KEY_NOTIFY
Required to request change notifications for a registry key or for subkeys of a registry key. | python.library.winreg#winreg.KEY_NOTIFY |
winreg.KEY_QUERY_VALUE
Required to query the values of a registry key. | python.library.winreg#winreg.KEY_QUERY_VALUE |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.