Issue #5262: Improved fix.
[python.git] / Doc / library / _winreg.rst
blob7876f8573b8fd4b53542d6815aba167321fa09e5
1 :mod:`_winreg` -- Windows registry access
2 =========================================
4 .. module:: _winreg
5    :platform: Windows
6    :synopsis: Routines and objects for manipulating the Windows registry.
7 .. sectionauthor:: Mark Hammond <MarkH@ActiveState.com>
9 .. note::
10    The :mod:`_winreg` module has been renamed to :mod:`winreg` in Python 3.0.
11    The :term:`2to3` tool will automatically adapt imports when converting your
12    sources to 3.0.
15 .. versionadded:: 2.0
17 These functions expose the Windows registry API to Python.  Instead of using an
18 integer as the registry handle, a handle object is used to ensure that the
19 handles are closed correctly, even if the programmer neglects to explicitly
20 close them.
22 This module exposes a very low-level interface to the Windows registry; it is
23 expected that in the future a new ``winreg``  module will be created offering a
24 higher-level interface to the registry API.
26 This module offers the following functions:
29 .. function:: CloseKey(hkey)
31    Closes a previously opened registry key. The hkey argument specifies a
32    previously opened key.
34    Note that if *hkey* is not closed using this method (or via
35    :meth:`handle.Close`), it is closed when the *hkey* object is destroyed by
36    Python.
39 .. function:: ConnectRegistry(computer_name, key)
41    Establishes a connection to a predefined registry handle on  another computer,
42    and returns a :dfn:`handle object`
44    *computer_name* is the name of the remote computer, of the  form
45    ``r"\\computername"``.  If ``None``, the local computer is used.
47    *key* is the predefined handle to connect to.
49    The return value is the handle of the opened key. If the function fails, a
50    :exc:`WindowsError` exception is  raised.
53 .. function:: CreateKey(key, sub_key)
55    Creates or opens the specified key, returning a :dfn:`handle object`
57    *key* is an already open key, or one of the predefined  :const:`HKEY_\*`
58    constants.
60    *sub_key* is a string that names the key this method opens  or creates.
62    If *key* is one of the predefined keys, *sub_key* may  be ``None``. In that
63    case, the handle returned is the same key handle  passed in to the function.
65    If the key already exists, this function opens the existing key.
67    The return value is the handle of the opened key. If the function fails, a
68    :exc:`WindowsError` exception is  raised.
71 .. function:: DeleteKey(key, sub_key)
73    Deletes the specified key.
75    *key* is an already open key, or any one of the predefined  :const:`HKEY_\*`
76    constants.
78    *sub_key* is a string that must be a subkey of the key  identified by the *key*
79    parameter.  This value must not be  ``None``, and the key may not have subkeys.
81    *This method can not delete keys with subkeys.*
83    If the method succeeds, the entire key, including all of its values, is removed.
84    If the method fails, a :exc:`WindowsError`  exception is raised.
87 .. function:: DeleteValue(key, value)
89    Removes a named value from a registry key.
91    *key* is an already open key, or one of the predefined  :const:`HKEY_\*`
92    constants.
94    *value* is a string that identifies the value to remove.
97 .. function:: EnumKey(key, index)
99    Enumerates subkeys of an open registry key, returning a string.
101    *key* is an already open key, or any one of the predefined  :const:`HKEY_\*`
102    constants.
104    *index* is an integer that identifies the index of the key to  retrieve.
106    The function retrieves the name of one subkey each time it  is called.  It is
107    typically called repeatedly until a  :exc:`WindowsError` exception  is
108    raised, indicating, no more values are available.
111 .. function:: EnumValue(key, index)
113    Enumerates values of an open registry key, returning a tuple.
115    *key* is an already open key, or any one of the predefined  :const:`HKEY_\*`
116    constants.
118    *index* is an integer that identifies the index of the value  to retrieve.
120    The function retrieves the name of one subkey each time it is  called. It is
121    typically called repeatedly, until a  :exc:`WindowsError` exception is
122    raised, indicating  no more values.
124    The result is a tuple of 3 items:
126    +-------+--------------------------------------------+
127    | Index | Meaning                                    |
128    +=======+============================================+
129    | ``0`` | A string that identifies the value name    |
130    +-------+--------------------------------------------+
131    | ``1`` | An object that holds the value data, and   |
132    |       | whose type depends on the underlying       |
133    |       | registry type                              |
134    +-------+--------------------------------------------+
135    | ``2`` | An integer that identifies the type of the |
136    |       | value data                                 |
137    +-------+--------------------------------------------+
140 .. function:: ExpandEnvironmentStrings(unicode)
142    Expands environment strings %NAME% in unicode string like const:`REG_EXPAND_SZ`::
144       >>> ExpandEnvironmentStrings(u"%windir%")
145       u"C:\\Windows"
147    .. versionadded:: 2.6
150 .. function:: FlushKey(key)
152    Writes all the attributes of a key to the registry.
154    *key* is an already open key, or one of the predefined  :const:`HKEY_\*`
155    constants.
157    It is not necessary to call :func:`FlushKey` to change a key. Registry changes are
158    flushed to disk by the registry using its lazy  flusher.  Registry changes are
159    also flushed to disk at system  shutdown.  Unlike :func:`CloseKey`, the
160    :func:`FlushKey` method  returns only when all the data has been written to the
161    registry. An application should only call :func:`FlushKey` if it requires
162    absolute  certainty that registry changes are on disk.
164    .. note::
166       If you don't know whether a :func:`FlushKey` call is required, it  probably
167       isn't.
170 .. function:: LoadKey(key, sub_key, file_name)
172    Creates a subkey under the specified key and stores registration  information
173    from a specified file into that subkey.
175    *key* is an already open key, or any of the predefined :const:`HKEY_\*`
176    constants.
178    *sub_key* is a string that identifies the sub_key to load.
180    *file_name* is the name of the file to load registry data from. This file must
181    have been created with the :func:`SaveKey` function. Under the file allocation
182    table (FAT) file system, the filename may not have an extension.
184    A call to LoadKey() fails if the calling process does not have the
185    :const:`SE_RESTORE_PRIVILEGE` privilege. Note that privileges are different than
186    permissions - see the Win32 documentation for more details.
188    If *key* is a handle returned by :func:`ConnectRegistry`,  then the path
189    specified in *fileName* is relative to the  remote computer.
191    The Win32 documentation implies *key* must be in the  :const:`HKEY_USER` or
192    :const:`HKEY_LOCAL_MACHINE` tree. This may or may not be true.
195 .. function:: OpenKey(key, sub_key[, res=0][, sam=KEY_READ])
197    Opens the specified key, returning a :dfn:`handle object`
199    *key* is an already open key, or any one of the predefined :const:`HKEY_\*`
200    constants.
202    *sub_key* is a string that identifies the sub_key to open.
204    *res* is a reserved integer, and must be zero.  The default is zero.
206    *sam* is an integer that specifies an access mask that describes  the desired
207    security access for the key.  Default is :const:`KEY_READ`
209    The result is a new handle to the specified key.
211    If the function fails, :exc:`WindowsError` is raised.
214 .. function:: OpenKeyEx()
216    The functionality of :func:`OpenKeyEx` is provided via :func:`OpenKey`, by the
217    use of default arguments.
220 .. function:: QueryInfoKey(key)
222    Returns information about a key, as a tuple.
224    *key* is an already open key, or one of the predefined  :const:`HKEY_\*`
225    constants.
227    The result is a tuple of 3 items:
229    +-------+---------------------------------------------+
230    | Index | Meaning                                     |
231    +=======+=============================================+
232    | ``0`` | An integer giving the number of sub keys    |
233    |       | this key has.                               |
234    +-------+---------------------------------------------+
235    | ``1`` | An integer giving the number of values this |
236    |       | key has.                                    |
237    +-------+---------------------------------------------+
238    | ``2`` | A long integer giving when the key was last |
239    |       | modified (if available) as 100's of         |
240    |       | nanoseconds since Jan 1, 1600.              |
241    +-------+---------------------------------------------+
244 .. function:: QueryValue(key, sub_key)
246    Retrieves the unnamed value for a key, as a string
248    *key* is an already open key, or one of the predefined  :const:`HKEY_\*`
249    constants.
251    *sub_key* is a string that holds the name of the subkey with which  the value is
252    associated.  If this parameter is ``None`` or empty, the  function retrieves the
253    value set by the :func:`SetValue` method  for the key identified by *key*.
255    Values in the registry have name, type, and data components. This method
256    retrieves the data for a key's first value that has a NULL name. But the
257    underlying API call doesn't return the type, so always use
258    :func:`QueryValueEx` if possible.
261 .. function:: QueryValueEx(key, value_name)
263    Retrieves the type and data for a specified value name associated with  an open
264    registry key.
266    *key* is an already open key, or one of the predefined  :const:`HKEY_\*`
267    constants.
269    *value_name* is a string indicating the value to query.
271    The result is a tuple of 2 items:
273    +-------+-----------------------------------------+
274    | Index | Meaning                                 |
275    +=======+=========================================+
276    | ``0`` | The value of the registry item.         |
277    +-------+-----------------------------------------+
278    | ``1`` | An integer giving the registry type for |
279    |       | this value.                             |
280    +-------+-----------------------------------------+
283 .. function:: SaveKey(key, file_name)
285    Saves the specified key, and all its subkeys to the specified file.
287    *key* is an already open key, or one of the predefined  :const:`HKEY_\*`
288    constants.
290    *file_name* is the name of the file to save registry data to. This file cannot
291    already exist. If this filename includes an extension, it cannot be used on file
292    allocation table (FAT) file systems by the :meth:`LoadKey`, :meth:`ReplaceKey`
293    or  :meth:`RestoreKey` methods.
295    If *key* represents a key on a remote computer, the path  described by
296    *file_name* is relative to the remote computer. The caller of this method must
297    possess the :const:`SeBackupPrivilege`  security privilege.  Note that
298    privileges are different than permissions  - see the Win32 documentation for
299    more details.
301    This function passes NULL for *security_attributes* to the API.
304 .. function:: SetValue(key, sub_key, type, value)
306    Associates a value with a specified key.
308    *key* is an already open key, or one of the predefined  :const:`HKEY_\*`
309    constants.
311    *sub_key* is a string that names the subkey with which the value  is associated.
313    *type* is an integer that specifies the type of the data. Currently this must be
314    :const:`REG_SZ`, meaning only strings are supported.  Use the :func:`SetValueEx`
315    function for support for other data types.
317    *value* is a string that specifies the new value.
319    If the key specified by the *sub_key* parameter does not exist, the SetValue
320    function creates it.
322    Value lengths are limited by available memory. Long values (more than 2048
323    bytes) should be stored as files with the filenames stored in the configuration
324    registry.  This helps the registry perform efficiently.
326    The key identified by the *key* parameter must have been  opened with
327    :const:`KEY_SET_VALUE` access.
330 .. function:: SetValueEx(key, value_name, reserved, type, value)
332    Stores data in the value field of an open registry key.
334    *key* is an already open key, or one of the predefined  :const:`HKEY_\*`
335    constants.
337    *value_name* is a string that names the subkey with which the  value is
338    associated.
340    *type* is an integer that specifies the type of the data.   This should be one
341    of the following constants defined in this module:
343    +----------------------------------+---------------------------------------------+
344    | Constant                         | Meaning                                     |
345    +==================================+=============================================+
346    | :const:`REG_BINARY`              | Binary data in any form.                    |
347    +----------------------------------+---------------------------------------------+
348    | :const:`REG_DWORD`               | A 32-bit number.                            |
349    +----------------------------------+---------------------------------------------+
350    | :const:`REG_DWORD_LITTLE_ENDIAN` | A 32-bit number in little-endian format.    |
351    +----------------------------------+---------------------------------------------+
352    | :const:`REG_DWORD_BIG_ENDIAN`    | A 32-bit number in big-endian format.       |
353    +----------------------------------+---------------------------------------------+
354    | :const:`REG_EXPAND_SZ`           | Null-terminated string containing           |
355    |                                  | references to environment variables         |
356    |                                  | (``%PATH%``).                               |
357    +----------------------------------+---------------------------------------------+
358    | :const:`REG_LINK`                | A Unicode symbolic link.                    |
359    +----------------------------------+---------------------------------------------+
360    | :const:`REG_MULTI_SZ`            | A sequence of null-terminated strings,      |
361    |                                  | terminated by two null characters.  (Python |
362    |                                  | handles  this termination automatically.)   |
363    +----------------------------------+---------------------------------------------+
364    | :const:`REG_NONE`                | No defined value type.                      |
365    +----------------------------------+---------------------------------------------+
366    | :const:`REG_RESOURCE_LIST`       | A device-driver resource list.              |
367    +----------------------------------+---------------------------------------------+
368    | :const:`REG_SZ`                  | A null-terminated string.                   |
369    +----------------------------------+---------------------------------------------+
371    *reserved* can be anything - zero is always passed to the  API.
373    *value* is a string that specifies the new value.
375    This method can also set additional value and type information for the specified
376    key.  The key identified by the key parameter must have been opened with
377    :const:`KEY_SET_VALUE` access.
379    To open the key, use the :func:`CreateKeyEx` or  :func:`OpenKey` methods.
381    Value lengths are limited by available memory. Long values (more than 2048
382    bytes) should be stored as files with the filenames stored in the configuration
383    registry.  This helps the registry perform efficiently.
386 .. _handle-object:
388 Registry Handle Objects
389 -----------------------
391 This object wraps a Windows HKEY object, automatically closing it when the
392 object is destroyed.  To guarantee cleanup, you can call either the
393 :meth:`Close` method on the object, or the  :func:`CloseKey` function.
395 All registry functions in this module return one of these objects.
397 All registry functions in this module which accept a handle object  also accept
398 an integer, however, use of the handle object is  encouraged.
400 Handle objects provide semantics for :meth:`__nonzero__` - thus  ::
402    if handle:
403        print "Yes"
405 will print ``Yes`` if the handle is currently valid (has not been closed or
406 detached).
408 The object also support comparison semantics, so handle objects will compare
409 true if they both reference the same underlying Windows handle value.
411 Handle objects can be converted to an integer (e.g., using the builtin
412 :func:`int` function), in which case the underlying Windows handle value is
413 returned.  You can also use the  :meth:`Detach` method to return the integer
414 handle, and also disconnect the Windows handle from the handle object.
417 .. method:: PyHKEY.Close()
419    Closes the underlying Windows handle.
421    If the handle is already closed, no error is raised.
424 .. method:: PyHKEY.Detach()
426    Detaches the Windows handle from the handle object.
428    The result is an integer (or long on 64 bit Windows) that holds the value of the
429    handle before it is detached.  If the handle is already detached or closed, this
430    will return zero.
432    After calling this function, the handle is effectively invalidated, but the
433    handle is not closed.  You would call this function when  you need the
434    underlying Win32 handle to exist beyond the lifetime  of the handle object.
436 .. method:: PyHKEY.__enter__()
437             PyHKEY.__exit__(\*exc_info)
439    The HKEY object implements :meth:`__enter__` and :meth:`__exit__` and thus
440    supports the context protocol for the :keyword:`with` statement::
442       with OpenKey(HKEY_LOCAL_MACHINE, "foo") as key:
443           # ... work with key ...
445    will automatically close *key* when control leaves the :keyword:`with` block.
447    .. versionadded:: 2.6