• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1:mod:`_winreg` -- Windows registry access
2=========================================
3
4.. module:: _winreg
5   :platform: Windows
6   :synopsis: Routines and objects for manipulating the Windows registry.
7.. sectionauthor:: Mark Hammond <MarkH@ActiveState.com>
8
9.. note::
10   The :mod:`_winreg` module has been renamed to :mod:`winreg` in Python 3.
11   The :term:`2to3` tool will automatically adapt imports when converting your
12   sources to Python 3.
13
14
15.. versionadded:: 2.0
16
17These functions expose the Windows registry API to Python.  Instead of using an
18integer as the registry handle, a :ref:`handle object <handle-object>` is used
19to ensure that the handles are closed correctly, even if the programmer neglects
20to explicitly close them.
21
22This module offers the following functions:
23
24
25.. function:: CloseKey(hkey)
26
27   Closes a previously opened registry key.  The *hkey* argument specifies a
28   previously opened key.
29
30   .. note::
31      If *hkey* is not closed using this method (or via :meth:`hkey.Close() <PyHKEY.Close>`),
32      it is closed when the *hkey* object is destroyed by Python.
33
34
35.. function:: ConnectRegistry(computer_name, key)
36
37   Establishes a connection to a predefined registry handle on another computer,
38   and returns a :ref:`handle object <handle-object>`.
39
40   *computer_name* is the name of the remote computer, of the form
41   ``r"\\computername"``.  If ``None``, the local computer is used.
42
43   *key* is the predefined handle to connect to.
44
45   The return value is the handle of the opened key. If the function fails, a
46   :exc:`WindowsError` exception is raised.
47
48
49.. function:: CreateKey(key, sub_key)
50
51   Creates or opens the specified key, returning a
52   :ref:`handle object <handle-object>`.
53
54   *key* is an already open key, or one of the predefined
55   :ref:`HKEY_* constants <hkey-constants>`.
56
57   *sub_key* is a string that names the key this method opens or creates.
58
59   If *key* is one of the predefined keys, *sub_key* may be ``None``. In that
60   case, the handle returned is the same key handle passed in to the function.
61
62   If the key already exists, this function opens the existing key.
63
64   The return value is the handle of the opened key. If the function fails, a
65   :exc:`WindowsError` exception is raised.
66
67
68.. function:: CreateKeyEx(key, sub_key[, res[, sam]])
69
70   Creates or opens the specified key, returning a
71   :ref:`handle object <handle-object>`.
72
73   *key* is an already open key, or one of the predefined
74   :ref:`HKEY_* constants <hkey-constants>`.
75
76   *sub_key* is a string that names the key this method opens or creates.
77
78   *res* is a reserved integer, and must be zero. The default is zero.
79
80   *sam* is an integer that specifies an access mask that describes the desired
81   security access for the key.  Default is :const:`KEY_ALL_ACCESS`.  See
82   :ref:`Access Rights <access-rights>` for other allowed values.
83
84
85   If *key* is one of the predefined keys, *sub_key* may be ``None``. In that
86   case, the handle returned is the same key handle passed in to the function.
87
88   If the key already exists, this function opens the existing key.
89
90   The return value is the handle of the opened key. If the function fails, a
91   :exc:`WindowsError` exception is raised.
92
93.. versionadded:: 2.7
94
95
96.. function:: DeleteKey(key, sub_key)
97
98   Deletes the specified key.
99
100   *key* is an already open key, or any one of the predefined
101   :ref:`HKEY_* constants <hkey-constants>`.
102
103   *sub_key* is a string that must be a subkey of the key identified by the *key*
104   parameter.  This value must not be ``None``, and the key may not have subkeys.
105
106   *This method can not delete keys with subkeys.*
107
108   If the method succeeds, the entire key, including all of its values, is removed.
109   If the method fails, a :exc:`WindowsError` exception is raised.
110
111
112.. function:: DeleteKeyEx(key, sub_key[, sam[, res]])
113
114   Deletes the specified key.
115
116   .. note::
117      The :func:`DeleteKeyEx` function is implemented with the RegDeleteKeyEx
118      Windows API function, which is specific to 64-bit versions of Windows.
119      See the `RegDeleteKeyEx documentation
120      <http://msdn.microsoft.com/en-us/library/ms724847%28VS.85%29.aspx>`__.
121
122   *key* is an already open key, or any one of the predefined
123   :ref:`HKEY_* constants <hkey-constants>`.
124
125   *sub_key* is a string that must be a subkey of the key identified by the
126   *key* parameter. This value must not be ``None``, and the key may not have
127   subkeys.
128
129   *res* is a reserved integer, and must be zero. The default is zero.
130
131   *sam* is an integer that specifies an access mask that describes the desired
132   security access for the key.  Default is :const:`KEY_WOW64_64KEY`.  See
133   :ref:`Access Rights <access-rights>` for other allowed values.
134
135
136   *This method can not delete keys with subkeys.*
137
138   If the method succeeds, the entire key, including all of its values, is
139   removed. If the method fails, a :exc:`WindowsError` exception is raised.
140
141   On unsupported Windows versions, :exc:`NotImplementedError` is raised.
142
143.. versionadded:: 2.7
144
145
146.. function:: DeleteValue(key, value)
147
148   Removes a named value from a registry key.
149
150   *key* is an already open key, or one of the predefined
151   :ref:`HKEY_* constants <hkey-constants>`.
152
153   *value* is a string that identifies the value to remove.
154
155
156.. function:: EnumKey(key, index)
157
158   Enumerates subkeys of an open registry key, returning a string.
159
160   *key* is an already open key, or any one of the predefined
161   :ref:`HKEY_* constants <hkey-constants>`.
162
163   *index* is an integer that identifies the index of the key to retrieve.
164
165   The function retrieves the name of one subkey each time it is called.  It is
166   typically called repeatedly until a :exc:`WindowsError` exception is
167   raised, indicating, no more values are available.
168
169
170.. function:: EnumValue(key, index)
171
172   Enumerates values of an open registry key, returning a tuple.
173
174   *key* is an already open key, or any one of the predefined
175   :ref:`HKEY_* constants <hkey-constants>`.
176
177   *index* is an integer that identifies the index of the value to retrieve.
178
179   The function retrieves the name of one subkey each time it is called. It is
180   typically called repeatedly, until a :exc:`WindowsError` exception is
181   raised, indicating no more values.
182
183   The result is a tuple of 3 items:
184
185   +-------+--------------------------------------------+
186   | Index | Meaning                                    |
187   +=======+============================================+
188   | ``0`` | A string that identifies the value name    |
189   +-------+--------------------------------------------+
190   | ``1`` | An object that holds the value data, and   |
191   |       | whose type depends on the underlying       |
192   |       | registry type                              |
193   +-------+--------------------------------------------+
194   | ``2`` | An integer that identifies the type of the |
195   |       | value data (see table in docs for          |
196   |       | :meth:`SetValueEx`)                        |
197   +-------+--------------------------------------------+
198
199
200.. function:: ExpandEnvironmentStrings(unicode)
201
202   Expands environment variable placeholders ``%NAME%`` in unicode strings like
203   :const:`REG_EXPAND_SZ`::
204
205      >>> ExpandEnvironmentStrings(u"%windir%")
206      u"C:\\Windows"
207
208   .. versionadded:: 2.6
209
210
211.. function:: FlushKey(key)
212
213   Writes all the attributes of a key to the registry.
214
215   *key* is an already open key, or one of the predefined
216   :ref:`HKEY_* constants <hkey-constants>`.
217
218   It is not necessary to call :func:`FlushKey` to change a key. Registry changes are
219   flushed to disk by the registry using its lazy flusher.  Registry changes are
220   also flushed to disk at system shutdown.  Unlike :func:`CloseKey`, the
221   :func:`FlushKey` method returns only when all the data has been written to the
222   registry. An application should only call :func:`FlushKey` if it requires
223   absolute certainty that registry changes are on disk.
224
225   .. note::
226
227      If you don't know whether a :func:`FlushKey` call is required, it probably
228      isn't.
229
230
231.. function:: LoadKey(key, sub_key, file_name)
232
233   Creates a subkey under the specified key and stores registration information
234   from a specified file into that subkey.
235
236   *key* is a handle returned by :func:`ConnectRegistry` or one of the constants
237   :const:`HKEY_USERS` or :const:`HKEY_LOCAL_MACHINE`.
238
239   *sub_key* is a string that identifies the subkey to load.
240
241   *file_name* is the name of the file to load registry data from. This file must
242   have been created with the :func:`SaveKey` function. Under the file allocation
243   table (FAT) file system, the filename may not have an extension.
244
245   A call to :func:`LoadKey` fails if the calling process does not have the
246   :const:`SE_RESTORE_PRIVILEGE` privilege.  Note that privileges are different
247   from permissions -- see the `RegLoadKey documentation
248   <http://msdn.microsoft.com/en-us/library/ms724889%28v=VS.85%29.aspx>`__ for
249   more details.
250
251   If *key* is a handle returned by :func:`ConnectRegistry`, then the path
252   specified in *file_name* is relative to the remote computer.
253
254
255.. function:: OpenKey(key, sub_key[, res[, sam]])
256
257   Opens the specified key, returning a :ref:`handle object <handle-object>`.
258
259   *key* is an already open key, or any one of the predefined
260   :ref:`HKEY_* constants <hkey-constants>`.
261
262   *sub_key* is a string that identifies the sub_key to open.
263
264   *res* is a reserved integer, and must be zero.  The default is zero.
265
266   *sam* is an integer that specifies an access mask that describes the desired
267   security access for the key.  Default is :const:`KEY_READ`.  See
268   :ref:`Access Rights <access-rights>` for other allowed values.
269
270   The result is a new handle to the specified key.
271
272   If the function fails, :exc:`WindowsError` is raised.
273
274
275.. function:: OpenKeyEx()
276
277   The functionality of :func:`OpenKeyEx` is provided via :func:`OpenKey`,
278   by the use of default arguments.
279
280
281.. function:: QueryInfoKey(key)
282
283   Returns information about a key, as a tuple.
284
285   *key* is an already open key, or one of the predefined
286   :ref:`HKEY_* constants <hkey-constants>`.
287
288   The result is a tuple of 3 items:
289
290   +-------+---------------------------------------------+
291   | Index | Meaning                                     |
292   +=======+=============================================+
293   | ``0`` | An integer giving the number of sub keys    |
294   |       | this key has.                               |
295   +-------+---------------------------------------------+
296   | ``1`` | An integer giving the number of values this |
297   |       | key has.                                    |
298   +-------+---------------------------------------------+
299   | ``2`` | A long integer giving when the key was last |
300   |       | modified (if available) as 100's of         |
301   |       | nanoseconds since Jan 1, 1601.              |
302   +-------+---------------------------------------------+
303
304
305.. function:: QueryValue(key, sub_key)
306
307   Retrieves the unnamed value for a key, as a string.
308
309   *key* is an already open key, or one of the predefined
310   :ref:`HKEY_* constants <hkey-constants>`.
311
312   *sub_key* is a string that holds the name of the subkey with which the value is
313   associated.  If this parameter is ``None`` or empty, the function retrieves the
314   value set by the :func:`SetValue` method for the key identified by *key*.
315
316   Values in the registry have name, type, and data components. This method
317   retrieves the data for a key's first value that has a NULL name. But the
318   underlying API call doesn't return the type, so always use
319   :func:`QueryValueEx` if possible.
320
321
322.. function:: QueryValueEx(key, value_name)
323
324   Retrieves the type and data for a specified value name associated with
325   an open registry key.
326
327   *key* is an already open key, or one of the predefined
328   :ref:`HKEY_* constants <hkey-constants>`.
329
330   *value_name* is a string indicating the value to query.
331
332   The result is a tuple of 2 items:
333
334   +-------+-----------------------------------------+
335   | Index | Meaning                                 |
336   +=======+=========================================+
337   | ``0`` | The value of the registry item.         |
338   +-------+-----------------------------------------+
339   | ``1`` | An integer giving the registry type for |
340   |       | this value (see table in docs for       |
341   |       | :meth:`SetValueEx`)                     |
342   +-------+-----------------------------------------+
343
344
345.. function:: SaveKey(key, file_name)
346
347   Saves the specified key, and all its subkeys to the specified file.
348
349   *key* is an already open key, or one of the predefined
350   :ref:`HKEY_* constants <hkey-constants>`.
351
352   *file_name* is the name of the file to save registry data to.  This file
353   cannot already exist. If this filename includes an extension, it cannot be
354   used on file allocation table (FAT) file systems by the :meth:`LoadKey`
355   method.
356
357   If *key* represents a key on a remote computer, the path described by
358   *file_name* is relative to the remote computer. The caller of this method must
359   possess the :const:`SeBackupPrivilege` security privilege.  Note that
360   privileges are different than permissions -- see the
361   `Conflicts Between User Rights and Permissions documentation
362   <http://msdn.microsoft.com/en-us/library/ms724878%28v=VS.85%29.aspx>`__
363   for more details.
364
365   This function passes NULL for *security_attributes* to the API.
366
367
368.. function:: SetValue(key, sub_key, type, value)
369
370   Associates a value with a specified key.
371
372   *key* is an already open key, or one of the predefined
373   :ref:`HKEY_* constants <hkey-constants>`.
374
375   *sub_key* is a string that names the subkey with which the value is associated.
376
377   *type* is an integer that specifies the type of the data. Currently this must be
378   :const:`REG_SZ`, meaning only strings are supported.  Use the :func:`SetValueEx`
379   function for support for other data types.
380
381   *value* is a string that specifies the new value.
382
383   If the key specified by the *sub_key* parameter does not exist, the SetValue
384   function creates it.
385
386   Value lengths are limited by available memory. Long values (more than 2048
387   bytes) should be stored as files with the filenames stored in the configuration
388   registry.  This helps the registry perform efficiently.
389
390   The key identified by the *key* parameter must have been opened with
391   :const:`KEY_SET_VALUE` access.
392
393
394.. function:: SetValueEx(key, value_name, reserved, type, value)
395
396   Stores data in the value field of an open registry key.
397
398   *key* is an already open key, or one of the predefined
399   :ref:`HKEY_* constants <hkey-constants>`.
400
401   *value_name* is a string that names the subkey with which the value is
402   associated.
403
404   *type* is an integer that specifies the type of the data. See
405   :ref:`Value Types <value-types>` for the available types.
406
407   *reserved* can be anything -- zero is always passed to the API.
408
409   *value* is a string that specifies the new value.
410
411   This method can also set additional value and type information for the specified
412   key.  The key identified by the key parameter must have been opened with
413   :const:`KEY_SET_VALUE` access.
414
415   To open the key, use the :func:`CreateKey` or :func:`OpenKey` methods.
416
417   Value lengths are limited by available memory. Long values (more than 2048
418   bytes) should be stored as files with the filenames stored in the configuration
419   registry.  This helps the registry perform efficiently.
420
421
422.. function:: DisableReflectionKey(key)
423
424   Disables registry reflection for 32-bit processes running on a 64-bit
425   operating system.
426
427   *key* is an already open key, or one of the predefined
428   :ref:`HKEY_* constants <hkey-constants>`.
429
430   Will generally raise :exc:`NotImplemented` if executed on a 32-bit
431   operating system.
432
433   If the key is not on the reflection list, the function succeeds but has no
434   effect. Disabling reflection for a key does not affect reflection of any
435   subkeys.
436
437
438.. function:: EnableReflectionKey(key)
439
440   Restores registry reflection for the specified disabled key.
441
442   *key* is an already open key, or one of the predefined
443   :ref:`HKEY_* constants <hkey-constants>`.
444
445   Will generally raise :exc:`NotImplemented` if executed on a 32-bit
446   operating system.
447
448   Restoring reflection for a key does not affect reflection of any subkeys.
449
450
451.. function:: QueryReflectionKey(key)
452
453   Determines the reflection state for the specified key.
454
455   *key* is an already open key, or one of the predefined
456   :ref:`HKEY_* constants <hkey-constants>`.
457
458   Returns ``True`` if reflection is disabled.
459
460   Will generally raise :exc:`NotImplemented` if executed on a 32-bit
461   operating system.
462
463
464.. _constants:
465
466Constants
467------------------
468
469The following constants are defined for use in many :mod:`_winreg` functions.
470
471.. _hkey-constants:
472
473HKEY_* Constants
474++++++++++++++++
475
476.. data:: HKEY_CLASSES_ROOT
477
478   Registry entries subordinate to this key define types (or classes) of
479   documents and the properties associated with those types. Shell and
480   COM applications use the information stored under this key.
481
482
483.. data:: HKEY_CURRENT_USER
484
485   Registry entries subordinate to this key define the preferences of
486   the current user. These preferences include the settings of
487   environment variables, data about program groups, colors, printers,
488   network connections, and application preferences.
489
490.. data:: HKEY_LOCAL_MACHINE
491
492   Registry entries subordinate to this key define the physical state
493   of the computer, including data about the bus type, system memory,
494   and installed hardware and software.
495
496.. data:: HKEY_USERS
497
498   Registry entries subordinate to this key define the default user
499   configuration for new users on the local computer and the user
500   configuration for the current user.
501
502.. data:: HKEY_PERFORMANCE_DATA
503
504   Registry entries subordinate to this key allow you to access
505   performance data. The data is not actually stored in the registry;
506   the registry functions cause the system to collect the data from
507   its source.
508
509
510.. data:: HKEY_CURRENT_CONFIG
511
512   Contains information about the current hardware profile of the
513   local computer system.
514
515.. data:: HKEY_DYN_DATA
516
517   This key is not used in versions of Windows after 98.
518
519
520.. _access-rights:
521
522Access Rights
523+++++++++++++
524
525For more information, see `Registry Key Security and Access
526<http://msdn.microsoft.com/en-us/library/ms724878%28v=VS.85%29.aspx>`__.
527
528.. data:: KEY_ALL_ACCESS
529
530   Combines the STANDARD_RIGHTS_REQUIRED, :const:`KEY_QUERY_VALUE`,
531   :const:`KEY_SET_VALUE`, :const:`KEY_CREATE_SUB_KEY`,
532   :const:`KEY_ENUMERATE_SUB_KEYS`, :const:`KEY_NOTIFY`,
533   and :const:`KEY_CREATE_LINK` access rights.
534
535.. data:: KEY_WRITE
536
537   Combines the STANDARD_RIGHTS_WRITE, :const:`KEY_SET_VALUE`, and
538   :const:`KEY_CREATE_SUB_KEY` access rights.
539
540.. data:: KEY_READ
541
542   Combines the STANDARD_RIGHTS_READ, :const:`KEY_QUERY_VALUE`,
543   :const:`KEY_ENUMERATE_SUB_KEYS`, and :const:`KEY_NOTIFY` values.
544
545.. data:: KEY_EXECUTE
546
547   Equivalent to :const:`KEY_READ`.
548
549.. data:: KEY_QUERY_VALUE
550
551   Required to query the values of a registry key.
552
553.. data:: KEY_SET_VALUE
554
555   Required to create, delete, or set a registry value.
556
557.. data:: KEY_CREATE_SUB_KEY
558
559   Required to create a subkey of a registry key.
560
561.. data:: KEY_ENUMERATE_SUB_KEYS
562
563   Required to enumerate the subkeys of a registry key.
564
565.. data:: KEY_NOTIFY
566
567   Required to request change notifications for a registry key or for
568   subkeys of a registry key.
569
570.. data:: KEY_CREATE_LINK
571
572   Reserved for system use.
573
574
575.. _64-bit-access-rights:
576
57764-bit Specific
578***************
579
580For more information, see `Accessing an Alternate Registry View
581<http://msdn.microsoft.com/en-us/library/aa384129(v=VS.85).aspx>`__.
582
583.. data:: KEY_WOW64_64KEY
584
585   Indicates that an application on 64-bit Windows should operate on
586   the 64-bit registry view.
587
588.. data:: KEY_WOW64_32KEY
589
590   Indicates that an application on 64-bit Windows should operate on
591   the 32-bit registry view.
592
593
594.. _value-types:
595
596Value Types
597+++++++++++
598
599For more information, see `Registry Value Types
600<http://msdn.microsoft.com/en-us/library/ms724884%28v=VS.85%29.aspx>`__.
601
602.. data:: REG_BINARY
603
604   Binary data in any form.
605
606.. data:: REG_DWORD
607
608   32-bit number.
609
610.. data:: REG_DWORD_LITTLE_ENDIAN
611
612   A 32-bit number in little-endian format.
613
614.. data:: REG_DWORD_BIG_ENDIAN
615
616   A 32-bit number in big-endian format.
617
618.. data:: REG_EXPAND_SZ
619
620   Null-terminated string containing references to environment
621   variables (``%PATH%``).
622
623.. data:: REG_LINK
624
625   A Unicode symbolic link.
626
627.. data:: REG_MULTI_SZ
628
629   A sequence of null-terminated strings, terminated by two null characters.
630   (Python handles this termination automatically.)
631
632.. data:: REG_NONE
633
634   No defined value type.
635
636.. data:: REG_RESOURCE_LIST
637
638   A device-driver resource list.
639
640.. data:: REG_FULL_RESOURCE_DESCRIPTOR
641
642   A hardware setting.
643
644.. data:: REG_RESOURCE_REQUIREMENTS_LIST
645
646   A hardware resource list.
647
648.. data:: REG_SZ
649
650   A null-terminated string.
651
652
653.. _handle-object:
654
655Registry Handle Objects
656-----------------------
657
658This object wraps a Windows HKEY object, automatically closing it when the
659object is destroyed.  To guarantee cleanup, you can call either the
660:meth:`~PyHKEY.Close` method on the object, or the :func:`CloseKey` function.
661
662All registry functions in this module return one of these objects.
663
664All registry functions in this module which accept a handle object also accept
665an integer, however, use of the handle object is encouraged.
666
667Handle objects provide semantics for :meth:`__nonzero__` -- thus::
668
669   if handle:
670       print "Yes"
671
672will print ``Yes`` if the handle is currently valid (has not been closed or
673detached).
674
675The object also support comparison semantics, so handle objects will compare
676true if they both reference the same underlying Windows handle value.
677
678Handle objects can be converted to an integer (e.g., using the built-in
679:func:`int` function), in which case the underlying Windows handle value is
680returned.  You can also use the :meth:`~PyHKEY.Detach` method to return the
681integer handle, and also disconnect the Windows handle from the handle object.
682
683
684.. method:: PyHKEY.Close()
685
686   Closes the underlying Windows handle.
687
688   If the handle is already closed, no error is raised.
689
690
691.. method:: PyHKEY.Detach()
692
693   Detaches the Windows handle from the handle object.
694
695   The result is an integer (or long on 64 bit Windows) that holds the value of the
696   handle before it is detached.  If the handle is already detached or closed, this
697   will return zero.
698
699   After calling this function, the handle is effectively invalidated, but the
700   handle is not closed.  You would call this function when you need the
701   underlying Win32 handle to exist beyond the lifetime of the handle object.
702
703.. method:: PyHKEY.__enter__()
704            PyHKEY.__exit__(\*exc_info)
705
706   The HKEY object implements :meth:`~object.__enter__` and
707   :meth:`~object.__exit__` and thus supports the context protocol for the
708   :keyword:`with` statement::
709
710      with OpenKey(HKEY_LOCAL_MACHINE, "foo") as key:
711          ...  # work with key
712
713   will automatically close *key* when control leaves the :keyword:`with` block.
714
715   .. versionadded:: 2.6
716
717