4 Windows Registry access module for Python.
6 * Simple registry access written by Mark Hammond in win32api
8 * Bill Tutt expanded the support significantly not long after.
9 * Numerous other people have submitted patches since then.
10 * Ripped from win32api module 03-Feb-2000 by Mark Hammond, and
11 basic Unicode support added.
17 #include "structmember.h"
18 #include "malloc.h" /* for alloca */
20 static BOOL
PyHKEY_AsHKEY(PyObject
*ob
, HKEY
*pRes
, BOOL bNoneOK
);
21 static PyObject
*PyHKEY_FromHKEY(HKEY h
);
22 static BOOL
PyHKEY_Close(PyObject
*obHandle
);
24 static char errNotAHandle
[] = "Object is not a handle";
26 /* The win32api module reports the function name that failed,
27 but this concept is not in the Python core.
28 Hopefully it will one day, and in the meantime I dont
29 want to lose this info...
31 #define PyErr_SetFromWindowsErrWithFunction(rc, fnname) \
32 PyErr_SetFromWindowsErr(rc)
34 /* Forward declares */
37 static char module_doc
[] =
38 "This module provides access to the Windows registry API.\n"
42 "CloseKey() - Closes a registry key.\n"
43 "ConnectRegistry() - Establishes a connection to a predefined registry handle\n"
44 " on another computer.\n"
45 "CreateKey() - Creates the specified key, or opens it if it already exists.\n"
46 "DeleteKey() - Deletes the specified key.\n"
47 "DeleteValue() - Removes a named value from the specified registry key.\n"
48 "EnumKey() - Enumerates subkeys of the specified open registry key.\n"
49 "EnumValue() - Enumerates values of the specified open registry key.\n"
50 "FlushKey() - Writes all the attributes of the specified key to the registry.\n"
51 "LoadKey() - Creates a subkey under HKEY_USER or HKEY_LOCAL_MACHINE and stores\n"
52 " registration information from a specified file into that subkey.\n"
53 "OpenKey() - Alias for <om win32api.RegOpenKeyEx>\n"
54 "OpenKeyEx() - Opens the specified key.\n"
55 "QueryValue() - Retrieves the value associated with the unnamed value for a\n"
56 " specified key in the registry.\n"
57 "QueryValueEx() - Retrieves the type and data for a specified value name\n"
58 " associated with an open registry key.\n"
59 "QueryInfoKey() - Returns information about the specified key.\n"
60 "SaveKey() - Saves the specified key, and all its subkeys a file.\n"
61 "SetValue() - Associates a value with a specified key.\n"
62 "SetValueEx() - Stores data in the value field of an open registry key.\n"
66 "HKEYType -- type object for HKEY objects\n"
67 "error -- exception raised for Win32 errors\n"
69 "Integer constants:\n"
70 "Many constants are defined - see the documentation for each function\n"
71 "to see what constants are used, and where.";
74 static char CloseKey_doc
[] =
75 "CloseKey(hkey) - Closes a previously opened registry key.\n"
77 "The hkey argument specifies a previously opened key.\n"
79 "Note that if the key is not closed using this method, it will be\n"
80 "closed when the hkey object is destroyed by Python.";
82 static char ConnectRegistry_doc
[] =
83 "key = ConnectRegistry(computer_name, key) - "
84 "Establishes a connection to a predefined registry handle on another computer.\n"
86 "computer_name is the name of the remote computer, of the form \\\\computername.\n"
87 " If None, the local computer is used.\n"
88 "key is the predefined handle to connect to.\n"
90 "The return value is the handle of the opened key.\n"
91 "If the function fails, an EnvironmentError exception is raised.";
93 static char CreateKey_doc
[] =
94 "key = CreateKey(key, sub_key) - Creates or opens the specified key.\n"
96 "key is an already open key, or one of the predefined HKEY_* constants\n"
97 "sub_key is a string that names the key this method opens or creates.\n"
98 " If key is one of the predefined keys, sub_key may be None. In that case,\n"
99 " the handle returned is the same key handle passed in to the function.\n"
101 "If the key already exists, this function opens the existing key\n"
103 "The return value is the handle of the opened key.\n"
104 "If the function fails, an exception is raised.";
106 static char DeleteKey_doc
[] =
107 "DeleteKey(key, sub_key) - Deletes the specified key.\n"
109 "key is an already open key, or any one of the predefined HKEY_* constants.\n"
110 "sub_key is a string that must be a subkey of the key identified by the key parameter.\n"
111 " This value must not be None, and the key may not have subkeys.\n"
113 "This method can not delete keys with subkeys.\n"
115 "If the method succeeds, the entire key, including all of its values,\n"
116 "is removed. If the method fails, an EnvironmentError exception is raised.";
118 static char DeleteValue_doc
[] =
119 "DeleteValue(key, value) - Removes a named value from a registry key.\n"
121 "key is an already open key, or any one of the predefined HKEY_* constants.\n"
122 "value is a string that identifies the value to remove.";
124 static char EnumKey_doc
[] =
125 "string = EnumKey(key, index) - Enumerates subkeys of an open registry key.\n"
127 "key is an already open key, or any one of the predefined HKEY_* constants.\n"
128 "index is an integer that identifies the index of the key to retrieve.\n"
130 "The function retrieves the name of one subkey each time it is called.\n"
131 "It is typically called repeatedly until an EnvironmentError exception is\n"
132 "raised, indicating no more values are available.\n";
134 static char EnumValue_doc
[] =
135 "tuple = EnumValue(key, index) - Enumerates values of an open registry key.\n"
136 "key is an already open key, or any one of the predefined HKEY_* constants.\n"
137 "index is an integer that identifies the index of the value to retrieve.\n"
139 "The function retrieves the name of one subkey each time it is called.\n"
140 "It is typically called repeatedly, until an EnvironmentError exception\n"
141 "is raised, indicating no more values.\n"
143 "The result is a tuple of 3 items:\n"
144 "value_name is a string that identifies the value.\n"
145 "value_data is an object that holds the value data, and whose type depends\n"
146 " on the underlying registry type.\n"
147 "data_type is an integer that identifies the type of the value data.";
149 static char FlushKey_doc
[] =
150 "FlushKey(key) - Writes all the attributes of a key to the registry.\n"
152 "key is an already open key, or any one of the predefined HKEY_* constants.\n"
154 "It is not necessary to call RegFlushKey to change a key.\n"
155 "Registry changes are flushed to disk by the registry using its lazy flusher.\n"
156 "Registry changes are also flushed to disk at system shutdown.\n"
157 "Unlike CloseKey(), the FlushKey() method returns only when all the data has\n"
158 "been written to the registry.\n"
159 "An application should only call FlushKey() if it requires absolute certainty that registry changes are on disk.\n"
160 "If you don't know whether a FlushKey() call is required, it probably isn't.\n";
162 static char LoadKey_doc
[] =
163 "LoadKey(key, sub_key, file_name) - Creates a subkey under the specified key\n"
164 "and stores registration information from a specified file into that subkey.\n"
166 "key is an already open key, or any one of the predefined HKEY_* constants.\n"
167 "sub_key is a string that identifies the sub_key to load\n"
168 "file_name is the name of the file to load registry data from.\n"
169 " This file must have been created with the SaveKey() function.\n"
170 " Under the file allocation table (FAT) file system, the filename may not\n"
171 "have an extension.\n"
173 "A call to LoadKey() fails if the calling process does not have the\n"
174 "SE_RESTORE_PRIVILEGE privilege.\n"
176 "If key is a handle returned by ConnectRegistry(), then the path specified\n"
177 "in fileName is relative to the remote computer.\n"
179 "The docs imply key must be in the HKEY_USER or HKEY_LOCAL_MACHINE tree";
181 static char OpenKey_doc
[] =
182 "key = OpenKey(key, sub_key, res = 0, sam = KEY_READ) - Opens the specified key.\n"
184 "key is an already open key, or any one of the predefined HKEY_* constants.\n"
185 "sub_key is a string that identifies the sub_key to open\n"
186 "res is a reserved integer, and must be zero. Default is zero.\n"
187 "sam is an integer that specifies an access mask that describes the desired\n"
188 " security access for the key. Default is KEY_READ\n"
190 "The result is a new handle to the specified key\n"
191 "If the function fails, an EnvironmentError exception is raised.\n";
193 static char OpenKeyEx_doc
[] =
196 static char QueryInfoKey_doc
[] =
197 "tuple = QueryInfoKey(key) - Returns information about a key.\n"
199 "key is an already open key, or any one of the predefined HKEY_* constants.\n"
201 "The result is a tuple of 3 items:"
202 "An integer that identifies the number of sub keys this key has.\n"
203 "An integer that identifies the number of values this key has.\n"
204 "A long integer that identifies when the key was last modified (if available)\n"
205 " as 100's of nanoseconds since Jan 1, 1600.\n";
207 static char QueryValue_doc
[] =
208 "string = QueryValue(key, sub_key) - retrieves the unnamed value for a key.\n"
210 "key is an already open key, or any one of the predefined HKEY_* constants.\n"
211 "sub_key is a string that holds the name of the subkey with which the value\n"
212 " is associated. If this parameter is None or empty, the function retrieves\n"
213 " the value set by the SetValue() method for the key identified by key."
215 "Values in the registry have name, type, and data components. This method\n"
216 "retrieves the data for a key's first value that has a NULL name.\n"
217 "But the underlying API call doesn't return the type, Lame Lame Lame, DONT USE THIS!!!";
219 static char QueryValueEx_doc
[] =
220 "value,type_id = QueryValueEx(key, value_name) - Retrieves the type and data for a specified value name associated with an open registry key.\n"
222 "key is an already open key, or any one of the predefined HKEY_* constants.\n"
223 "value_name is a string indicating the value to query";
225 static char SaveKey_doc
[] =
226 "SaveKey(key, file_name) - Saves the specified key, and all its subkeys to the specified file.\n"
228 "key is an already open key, or any one of the predefined HKEY_* constants.\n"
229 "file_name is the name of the file to save registry data to.\n"
230 " This file cannot already exist. If this filename includes an extension,\n"
231 " it cannot be used on file allocation table (FAT) file systems by the\n"
232 " LoadKey(), ReplaceKey() or RestoreKey() methods.\n"
234 "If key represents a key on a remote computer, the path described by\n"
235 "file_name is relative to the remote computer.\n"
236 "The caller of this method must possess the SeBackupPrivilege security privilege.\n"
237 "This function passes NULL for security_attributes to the API.";
239 static char SetValue_doc
[] =
240 "SetValue(key, sub_key, type, value) - Associates a value with a specified key.\n"
242 "key is an already open key, or any one of the predefined HKEY_* constants.\n"
243 "sub_key is a string that names the subkey with which the value is associated.\n"
244 "type is an integer that specifies the type of the data. Currently this\n"
245 " must be REG_SZ, meaning only strings are supported.\n"
246 "value is a string that specifies the new value.\n"
248 "If the key specified by the sub_key parameter does not exist, the SetValue\n"
249 "function creates it.\n"
251 "Value lengths are limited by available memory. Long values (more than\n"
252 "2048 bytes) should be stored as files with the filenames stored in \n"
253 "the configuration registry. This helps the registry perform efficiently.\n"
255 "The key identified by the key parameter must have been opened with\n"
256 "KEY_SET_VALUE access.";
258 static char SetValueEx_doc
[] =
259 "SetValueEx(key, value_name, reserved, type, value) - Stores data in the value field of an open registry key.\n"
261 "key is an already open key, or any one of the predefined HKEY_* constants.\n"
262 "sub_key is a string that names the subkey with which the value is associated.\n"
263 "type is an integer that specifies the type of the data. This should be one of:\n"
264 " REG_BINARY -- Binary data in any form.\n"
265 " REG_DWORD -- A 32-bit number.\n"
266 " REG_DWORD_LITTLE_ENDIAN -- A 32-bit number in little-endian format.\n"
267 " REG_DWORD_BIG_ENDIAN -- A 32-bit number in big-endian format.\n"
268 " REG_EXPAND_SZ -- A null-terminated string that contains unexpanded references\n"
269 " to environment variables (for example, %PATH%).\n"
270 " REG_LINK -- A Unicode symbolic link.\n"
271 " REG_MULTI_SZ -- An sequence of null-terminated strings, terminated by\n"
272 " two null characters. Note that Python handles this\n"
273 " termination automatically.\n"
274 " REG_NONE -- No defined value type.\n"
275 " REG_RESOURCE_LIST -- A device-driver resource list.\n"
276 " REG_SZ -- A null-terminated string.\n"
277 "reserved can be anything - zero is always passed to the API.\n"
278 "value is a string that specifies the new value.\n"
280 "This method can also set additional value and type information for the\n"
281 "specified key. The key identified by the key parameter must have been\n"
282 "opened with KEY_SET_VALUE access.\n"
284 "To open the key, use the CreateKeyEx() or OpenKeyEx() methods.\n"
286 "Value lengths are limited by available memory. Long values (more than\n"
287 "2048 bytes) should be stored as files with the filenames stored in \n"
288 "the configuration registry. This helps the registry perform efficiently.\n";
290 /* PyHKEY docstrings */
291 static char PyHKEY_doc
[] =
292 "PyHKEY Object - A Python object, representing a win32 registry key.\n"
294 "This object wraps a Windows HKEY object, automatically closing it when\n"
295 "the object is destroyed. To guarantee cleanup, you can call either\n"
296 "the Close() method on the PyHKEY, or the CloseKey() method.\n"
298 "All functions which accept a handle object also accept an integer - \n"
299 "however, use of the handle object is encouraged.\n"
302 "Close() - Closes the underlying handle.\n"
303 "Detach() - Returns the integer Win32 handle, detaching it from the object\n"
306 "handle - The integer Win32 handle.\n"
309 "__nonzero__ - Handles with an open object return true, otherwise false.\n"
310 "__int__ - Converting a handle to an integer returns the Win32 handle.\n"
311 "__cmp__ - Handle objects are compared using the handle value.\n";
314 static char PyHKEY_Close_doc
[] =
315 "key.Close() - Closes the underlying Windows handle.\n"
317 "If the handle is already closed, no error is raised.";
319 static char PyHKEY_Detach_doc
[] =
320 "int = key.Detach() - Detaches the Windows handle from the handle object.\n"
322 "The result is the value of the handle before it is detached. If the\n"
323 "handle is already detached, this will return zero.\n"
325 "After calling this function, the handle is effectively invalidated,\n"
326 "but the handle is not closed. You would call this function when you\n"
327 "need the underlying win32 handle to exist beyond the lifetime of the\n"
329 "On 64 bit windows, the result of this function is a long integer\n";
332 /************************************************************************
334 The PyHKEY object definition
336 ************************************************************************/
342 #define PyHKEY_Check(op) ((op)->ob_type == &PyHKEY_Type)
344 static char *failMsg
= "bad operand type";
347 PyHKEY_unaryFailureFunc(PyObject
*ob
)
349 PyErr_SetString(PyExc_TypeError
, failMsg
);
353 PyHKEY_binaryFailureFunc(PyObject
*ob1
, PyObject
*ob2
)
355 PyErr_SetString(PyExc_TypeError
, failMsg
);
359 PyHKEY_ternaryFailureFunc(PyObject
*ob1
, PyObject
*ob2
, PyObject
*ob3
)
361 PyErr_SetString(PyExc_TypeError
, failMsg
);
366 PyHKEY_deallocFunc(PyObject
*ob
)
368 /* Can not call PyHKEY_Close, as the ob->tp_type
369 has already been cleared, thus causing the type
372 PyHKEYObject
*obkey
= (PyHKEYObject
*)ob
;
374 RegCloseKey((HKEY
)obkey
->hkey
);
379 PyHKEY_nonzeroFunc(PyObject
*ob
)
381 return ((PyHKEYObject
*)ob
)->hkey
!= 0;
385 PyHKEY_intFunc(PyObject
*ob
)
387 PyHKEYObject
*pyhkey
= (PyHKEYObject
*)ob
;
388 return PyLong_FromVoidPtr(pyhkey
->hkey
);
392 PyHKEY_printFunc(PyObject
*ob
, FILE *fp
, int flags
)
394 PyHKEYObject
*pyhkey
= (PyHKEYObject
*)ob
;
396 wsprintf(resBuf
, "<PyHKEY at %p (%p)>",
403 PyHKEY_strFunc(PyObject
*ob
)
405 PyHKEYObject
*pyhkey
= (PyHKEYObject
*)ob
;
407 wsprintf(resBuf
, "<PyHKEY:%p>", pyhkey
->hkey
);
408 return PyString_FromString(resBuf
);
412 PyHKEY_compareFunc(PyObject
*ob1
, PyObject
*ob2
)
414 PyHKEYObject
*pyhkey1
= (PyHKEYObject
*)ob1
;
415 PyHKEYObject
*pyhkey2
= (PyHKEYObject
*)ob2
;
416 return pyhkey1
== pyhkey2
? 0 :
417 (pyhkey1
< pyhkey2
? -1 : 1);
421 PyHKEY_hashFunc(PyObject
*ob
)
423 /* Just use the address.
424 XXX - should we use the handle value?
426 return _Py_HashPointer(ob
);
430 static PyNumberMethods PyHKEY_NumberMethods
=
432 PyHKEY_binaryFailureFunc
, /* nb_add */
433 PyHKEY_binaryFailureFunc
, /* nb_subtract */
434 PyHKEY_binaryFailureFunc
, /* nb_multiply */
435 PyHKEY_binaryFailureFunc
, /* nb_divide */
436 PyHKEY_binaryFailureFunc
, /* nb_remainder */
437 PyHKEY_binaryFailureFunc
, /* nb_divmod */
438 PyHKEY_ternaryFailureFunc
, /* nb_power */
439 PyHKEY_unaryFailureFunc
, /* nb_negative */
440 PyHKEY_unaryFailureFunc
, /* nb_positive */
441 PyHKEY_unaryFailureFunc
, /* nb_absolute */
442 PyHKEY_nonzeroFunc
, /* nb_nonzero */
443 PyHKEY_unaryFailureFunc
, /* nb_invert */
444 PyHKEY_binaryFailureFunc
, /* nb_lshift */
445 PyHKEY_binaryFailureFunc
, /* nb_rshift */
446 PyHKEY_binaryFailureFunc
, /* nb_and */
447 PyHKEY_binaryFailureFunc
, /* nb_xor */
448 PyHKEY_binaryFailureFunc
, /* nb_or */
449 0, /* nb_coerce (allowed to be zero) */
450 PyHKEY_intFunc
, /* nb_int */
451 PyHKEY_unaryFailureFunc
, /* nb_long */
452 PyHKEY_unaryFailureFunc
, /* nb_float */
453 PyHKEY_unaryFailureFunc
, /* nb_oct */
454 PyHKEY_unaryFailureFunc
, /* nb_hex */
458 /* fwd declare __getattr__ */
459 static PyObject
*PyHKEY_getattr(PyObject
*self
, char *name
);
461 /* The type itself */
462 PyTypeObject PyHKEY_Type
=
464 PyObject_HEAD_INIT(0) /* fill in type at module init */
467 sizeof(PyHKEYObject
),
469 PyHKEY_deallocFunc
, /* tp_dealloc */
470 PyHKEY_printFunc
, /* tp_print */
471 PyHKEY_getattr
, /* tp_getattr */
473 PyHKEY_compareFunc
, /* tp_compare */
475 &PyHKEY_NumberMethods
, /* tp_as_number */
476 0, /* tp_as_sequence */
477 0, /* tp_as_mapping */
478 PyHKEY_hashFunc
, /* tp_hash */
480 PyHKEY_strFunc
, /* tp_str */
483 0, /* tp_as_buffer */
485 PyHKEY_doc
, /* tp_doc */
488 #define OFF(e) offsetof(PyHKEYObject, e)
490 static struct memberlist PyHKEY_memberlist
[] = {
491 {"handle", T_INT
, OFF(hkey
)},
492 {NULL
} /* Sentinel */
495 /************************************************************************
497 The PyHKEY object methods
499 ************************************************************************/
501 PyHKEY_CloseMethod(PyObject
*self
, PyObject
*args
)
503 if (!PyArg_ParseTuple(args
, ":Close"))
505 if (!PyHKEY_Close(self
))
512 PyHKEY_DetachMethod(PyObject
*self
, PyObject
*args
)
515 PyHKEYObject
*pThis
= (PyHKEYObject
*)self
;
516 if (!PyArg_ParseTuple(args
, ":Detach"))
518 ret
= (void*)pThis
->hkey
;
520 return PyLong_FromVoidPtr(ret
);
523 static struct PyMethodDef PyHKEY_methods
[] = {
524 {"Close", PyHKEY_CloseMethod
, 1, PyHKEY_Close_doc
},
525 {"Detach", PyHKEY_DetachMethod
, 1, PyHKEY_Detach_doc
},
529 /*static*/ PyObject
*
530 PyHKEY_getattr(PyObject
*self
, char *name
)
534 res
= Py_FindMethod(PyHKEY_methods
, self
, name
);
538 if (strcmp(name
, "handle") == 0)
539 return PyLong_FromVoidPtr(((PyHKEYObject
*)self
)->hkey
);
540 return PyMember_Get((char *)self
, PyHKEY_memberlist
, name
);
543 /************************************************************************
544 The public PyHKEY API (well, not public yet :-)
545 ************************************************************************/
547 PyHKEY_New(HKEY hInit
)
549 PyHKEYObject
*key
= PyObject_NEW(PyHKEYObject
, &PyHKEY_Type
);
552 return (PyObject
*)key
;
556 PyHKEY_Close(PyObject
*ob_handle
)
561 if (!PyHKEY_Check(ob_handle
)) {
562 PyErr_SetString(PyExc_TypeError
, "bad operand type");
565 key
= (PyHKEYObject
*)ob_handle
;
566 rc
= key
->hkey
? RegCloseKey((HKEY
)key
->hkey
) : ERROR_SUCCESS
;
568 if (rc
!= ERROR_SUCCESS
)
569 PyErr_SetFromWindowsErrWithFunction(rc
, "RegCloseKey");
570 return rc
== ERROR_SUCCESS
;
574 PyHKEY_AsHKEY(PyObject
*ob
, HKEY
*pHANDLE
, BOOL bNoneOK
)
580 "None is not a valid HKEY in this context");
585 else if (PyHKEY_Check(ob
)) {
586 PyHKEYObject
*pH
= (PyHKEYObject
*)ob
;
589 else if (PyInt_Check(ob
) || PyLong_Check(ob
)) {
590 /* We also support integers */
592 *pHANDLE
= (HKEY
)PyLong_AsVoidPtr(ob
);
593 if (PyErr_Occurred())
599 "The object is not a PyHKEY object");
606 PyHKEY_FromHKEY(HKEY h
)
610 /* PyObject_New is inlined */
611 op
= (PyHKEYObject
*) PyObject_MALLOC(sizeof(PyHKEYObject
));
613 return PyErr_NoMemory();
614 PyObject_INIT(op
, &PyHKEY_Type
);
616 return (PyObject
*)op
;
620 /************************************************************************
622 ************************************************************************/
624 PyWinObject_CloseHKEY(PyObject
*obHandle
)
627 if (PyHKEY_Check(obHandle
)) {
628 ok
= PyHKEY_Close(obHandle
);
630 #if SIZEOF_LONG >= SIZEOF_HKEY
631 else if (PyInt_Check(obHandle
)) {
632 long rc
= RegCloseKey((HKEY
)PyInt_AsLong(obHandle
));
633 ok
= (rc
== ERROR_SUCCESS
);
635 PyErr_SetFromWindowsErrWithFunction(rc
, "RegCloseKey");
638 else if (PyLong_Check(obHandle
)) {
639 long rc
= RegCloseKey((HKEY
)PyLong_AsVoidPtr(obHandle
));
640 ok
= (rc
== ERROR_SUCCESS
);
642 PyErr_SetFromWindowsErrWithFunction(rc
, "RegCloseKey");
648 "A handle must be a HKEY object or an integer");
656 Private Helper functions for the registry interfaces
658 ** Note that fixupMultiSZ and countString have both had changes
659 ** made to support "incorrect strings". The registry specification
660 ** calls for strings to be terminated with 2 null bytes. It seems
661 ** some commercial packages install strings which dont conform,
662 ** causing this code to fail - however, "regedit" etc still work
663 ** with these strings (ie only we dont!).
666 fixupMultiSZ(char **str
, char *data
, int len
)
673 for (P
= data
, i
= 0; P
< Q
&& *P
!= '\0'; P
++, i
++) {
675 for(; *P
!= '\0'; P
++)
681 countStrings(char *data
, int len
)
685 char *Q
= data
+ len
;
687 for (P
= data
, strings
= 0; P
< Q
&& *P
!= '\0'; P
++, strings
++)
688 for (; P
< Q
&& *P
!= '\0'; P
++)
693 /* Convert PyObject into Registry data.
694 Allocates space as needed. */
696 Py2Reg(PyObject
*value
, DWORD typ
, BYTE
**retDataBuf
, DWORD
*retDataSize
)
701 if (value
!= Py_None
&& !PyInt_Check(value
))
703 *retDataBuf
= (BYTE
*)PyMem_NEW(DWORD
, sizeof(DWORD
));
704 if (*retDataBuf
==NULL
){
708 *retDataSize
= sizeof(DWORD
);
709 if (value
== Py_None
) {
711 memcpy(*retDataBuf
, &zero
, sizeof(DWORD
));
715 &PyInt_AS_LONG((PyIntObject
*)value
),
722 if (value
== Py_None
)
725 if (PyUnicode_Check(value
)) {
726 value
= PyUnicode_AsEncodedString(
734 if (!PyString_Check(value
))
736 *retDataSize
= 1 + strlen(
738 (PyStringObject
*)value
));
740 *retDataBuf
= (BYTE
*)PyMem_NEW(DWORD
, *retDataSize
);
741 if (*retDataBuf
==NULL
){
745 if (value
== Py_None
)
746 strcpy((char *)*retDataBuf
, "");
748 strcpy((char *)*retDataBuf
,
750 (PyStringObject
*)value
));
759 PyObject
**obs
= NULL
;
761 if (value
== Py_None
)
764 if (!PyList_Check(value
))
766 i
= PyList_Size(value
);
768 obs
= malloc(sizeof(PyObject
*) * i
);
769 memset(obs
, 0, sizeof(PyObject
*) * i
);
770 for (j
= 0; j
< i
; j
++)
774 (PyListObject
*)value
,j
);
775 if (PyString_Check(t
)) {
778 } else if (PyUnicode_Check(t
)) {
779 obs
[j
] = PyUnicode_AsEncodedString(
789 (PyStringObject
*)obs
[j
]));
792 *retDataSize
= size
+ 1;
793 *retDataBuf
= (BYTE
*)PyMem_NEW(char,
795 if (*retDataBuf
==NULL
){
799 P
= (char *)*retDataBuf
;
801 for (j
= 0; j
< i
; j
++)
807 (PyStringObject
*)t
));
810 (PyStringObject
*)t
));
813 /* And doubly-terminate the list... */
819 for (j
= 0; j
< i
; j
++)
827 /* ALSO handle ALL unknown data types here. Even if we can't
828 support it natively, we should handle the bits. */
830 if (value
== Py_None
)
834 PyBufferProcs
*pb
= value
->ob_type
->tp_as_buffer
;
836 PyErr_Format(PyExc_TypeError
,
837 "Objects of type '%s' can not "
838 "be used as binary registry values",
839 value
->ob_type
->tp_name
);
842 *retDataSize
= (*pb
->bf_getreadbuffer
)(value
, 0, &src_buf
);
843 *retDataBuf
= (BYTE
*)PyMem_NEW(char,
845 if (*retDataBuf
==NULL
){
849 memcpy(*retDataBuf
, src_buf
, *retDataSize
);
856 /* Convert Registry data into PyObject*/
858 Reg2Py(char *retDataBuf
, DWORD retDataSize
, DWORD typ
)
864 if (retDataSize
== 0)
865 obData
= Py_BuildValue("i", 0);
867 obData
= Py_BuildValue("i",
872 /* retDataBuf may or may not have a trailing NULL in
874 if (retDataSize
&& retDataBuf
[retDataSize
-1] == '\0')
878 obData
= PyUnicode_DecodeMBCS(retDataBuf
,
883 if (retDataSize
== 0)
884 obData
= PyList_New(0);
888 int s
= countStrings(retDataBuf
, retDataSize
);
889 char **str
= (char **)malloc(sizeof(char *)*s
);
891 return PyErr_NoMemory();
893 fixupMultiSZ(str
, retDataBuf
, retDataSize
);
894 obData
= PyList_New(s
);
897 for (index
= 0; index
< s
; index
++)
899 size_t len
= _mbstrlen(str
[index
]);
901 PyErr_SetString(PyExc_OverflowError
,
902 "registry string is too long for a Python string");
906 PyList_SetItem(obData
,
908 PyUnicode_DecodeMBCS(
909 (const char *)str
[index
],
919 /* ALSO handle ALL unknown data types here. Even if we can't
920 support it natively, we should handle the bits. */
922 if (retDataSize
== 0) {
927 obData
= Py_BuildValue("s#",
938 /* The Python methods */
941 PyCloseKey(PyObject
*self
, PyObject
*args
)
944 if (!PyArg_ParseTuple(args
, "O:CloseKey", &obKey
))
946 if (!PyHKEY_Close(obKey
))
953 PyConnectRegistry(PyObject
*self
, PyObject
*args
)
957 char *szCompName
= NULL
;
960 if (!PyArg_ParseTuple(args
, "zO:ConnectRegistry", &szCompName
, &obKey
))
962 if (!PyHKEY_AsHKEY(obKey
, &hKey
, FALSE
))
964 rc
= RegConnectRegistry(szCompName
, hKey
, &retKey
);
965 if (rc
!= ERROR_SUCCESS
)
966 return PyErr_SetFromWindowsErrWithFunction(rc
,
968 return PyHKEY_FromHKEY(retKey
);
972 PyCreateKey(PyObject
*self
, PyObject
*args
)
979 if (!PyArg_ParseTuple(args
, "Oz:CreateKey", &obKey
, &subKey
))
981 if (!PyHKEY_AsHKEY(obKey
, &hKey
, FALSE
))
983 rc
= RegCreateKey(hKey
, subKey
, &retKey
);
984 if (rc
!= ERROR_SUCCESS
)
985 return PyErr_SetFromWindowsErrWithFunction(rc
, "CreateKey");
986 return PyHKEY_FromHKEY(retKey
);
990 PyDeleteKey(PyObject
*self
, PyObject
*args
)
996 if (!PyArg_ParseTuple(args
, "Os:DeleteKey", &obKey
, &subKey
))
998 if (!PyHKEY_AsHKEY(obKey
, &hKey
, FALSE
))
1000 rc
= RegDeleteKey(hKey
, subKey
);
1001 if (rc
!= ERROR_SUCCESS
)
1002 return PyErr_SetFromWindowsErrWithFunction(rc
, "RegDeleteKey");
1008 PyDeleteValue(PyObject
*self
, PyObject
*args
)
1014 if (!PyArg_ParseTuple(args
, "Oz:DeleteValue", &obKey
, &subKey
))
1016 if (!PyHKEY_AsHKEY(obKey
, &hKey
, FALSE
))
1018 Py_BEGIN_ALLOW_THREADS
1019 rc
= RegDeleteValue(hKey
, subKey
);
1020 Py_END_ALLOW_THREADS
1021 if (rc
!=ERROR_SUCCESS
)
1022 return PyErr_SetFromWindowsErrWithFunction(rc
,
1029 PyEnumKey(PyObject
*self
, PyObject
*args
)
1038 if (!PyArg_ParseTuple(args
, "Oi:EnumKey", &obKey
, &index
))
1040 if (!PyHKEY_AsHKEY(obKey
, &hKey
, FALSE
))
1043 if ((rc
= RegQueryInfoKey(hKey
, NULL
, NULL
, NULL
, NULL
, &len
,
1044 NULL
, NULL
, NULL
, NULL
, NULL
, NULL
))
1046 return PyErr_SetFromWindowsErrWithFunction(rc
,
1048 ++len
; /* include null terminator */
1049 retBuf
= (char *)alloca(len
);
1051 if ((rc
= RegEnumKey(hKey
, index
, retBuf
, len
)) != ERROR_SUCCESS
)
1052 return PyErr_SetFromWindowsErrWithFunction(rc
, "RegEnumKey");
1053 return Py_BuildValue("s", retBuf
);
1057 PyEnumValue(PyObject
*self
, PyObject
*args
)
1071 if (!PyArg_ParseTuple(args
, "Oi:EnumValue", &obKey
, &index
))
1073 if (!PyHKEY_AsHKEY(obKey
, &hKey
, FALSE
))
1076 if ((rc
= RegQueryInfoKey(hKey
, NULL
, NULL
, NULL
, NULL
, NULL
, NULL
,
1078 &retValueSize
, &retDataSize
, NULL
, NULL
))
1080 return PyErr_SetFromWindowsErrWithFunction(rc
,
1082 ++retValueSize
; /* include null terminators */
1084 retValueBuf
= (char *)alloca(retValueSize
);
1085 retDataBuf
= (char *)alloca(retDataSize
);
1087 Py_BEGIN_ALLOW_THREADS
1088 rc
= RegEnumValue(hKey
,
1096 Py_END_ALLOW_THREADS
1098 if (rc
!= ERROR_SUCCESS
)
1099 return PyErr_SetFromWindowsErrWithFunction(rc
,
1101 obData
= Reg2Py(retDataBuf
, retDataSize
, typ
);
1104 retVal
= Py_BuildValue("sOi", retValueBuf
, obData
, typ
);
1110 PyFlushKey(PyObject
*self
, PyObject
*args
)
1115 if (!PyArg_ParseTuple(args
, "O:FlushKey", &obKey
))
1117 if (!PyHKEY_AsHKEY(obKey
, &hKey
, FALSE
))
1119 Py_BEGIN_ALLOW_THREADS
1120 rc
= RegFlushKey(hKey
);
1121 Py_END_ALLOW_THREADS
1122 if (rc
!= ERROR_SUCCESS
)
1123 return PyErr_SetFromWindowsErrWithFunction(rc
, "RegFlushKey");
1128 PyLoadKey(PyObject
*self
, PyObject
*args
)
1136 if (!PyArg_ParseTuple(args
, "Oss:LoadKey", &obKey
, &subKey
, &fileName
))
1138 if (!PyHKEY_AsHKEY(obKey
, &hKey
, FALSE
))
1140 Py_BEGIN_ALLOW_THREADS
1141 rc
= RegLoadKey(hKey
, subKey
, fileName
);
1142 Py_END_ALLOW_THREADS
1143 if (rc
!= ERROR_SUCCESS
)
1144 return PyErr_SetFromWindowsErrWithFunction(rc
, "RegLoadKey");
1150 PyOpenKey(PyObject
*self
, PyObject
*args
)
1159 REGSAM sam
= KEY_READ
;
1160 if (!PyArg_ParseTuple(args
, "Oz|ii:OpenKey", &obKey
, &subKey
,
1163 if (!PyHKEY_AsHKEY(obKey
, &hKey
, FALSE
))
1166 Py_BEGIN_ALLOW_THREADS
1167 rc
= RegOpenKeyEx(hKey
, subKey
, res
, sam
, &retKey
);
1168 Py_END_ALLOW_THREADS
1169 if (rc
!= ERROR_SUCCESS
)
1170 return PyErr_SetFromWindowsErrWithFunction(rc
, "RegOpenKeyEx");
1171 return PyHKEY_FromHKEY(retKey
);
1176 PyQueryInfoKey(PyObject
*self
, PyObject
*args
)
1181 DWORD nSubKeys
, nValues
;
1186 if (!PyArg_ParseTuple(args
, "O:QueryInfoKey", &obKey
))
1188 if (!PyHKEY_AsHKEY(obKey
, &hKey
, FALSE
))
1190 if ((rc
= RegQueryInfoKey(hKey
, NULL
, NULL
, 0, &nSubKeys
, NULL
, NULL
,
1191 &nValues
, NULL
, NULL
, NULL
, &ft
))
1193 return PyErr_SetFromWindowsErrWithFunction(rc
, "RegQueryInfoKey");
1194 li
.LowPart
= ft
.dwLowDateTime
;
1195 li
.HighPart
= ft
.dwHighDateTime
;
1196 l
= PyLong_FromLongLong(li
.QuadPart
);
1199 ret
= Py_BuildValue("iiO", nSubKeys
, nValues
, l
);
1205 PyQueryValue(PyObject
*self
, PyObject
*args
)
1214 if (!PyArg_ParseTuple(args
, "Oz:QueryValue", &obKey
, &subKey
))
1217 if (!PyHKEY_AsHKEY(obKey
, &hKey
, FALSE
))
1219 if ((rc
= RegQueryValue(hKey
, subKey
, NULL
, &bufSize
))
1221 return PyErr_SetFromWindowsErrWithFunction(rc
,
1223 retBuf
= (char *)alloca(bufSize
);
1224 if ((rc
= RegQueryValue(hKey
, subKey
, retBuf
, &bufSize
))
1226 return PyErr_SetFromWindowsErrWithFunction(rc
,
1228 return Py_BuildValue("s", retBuf
);
1232 PyQueryValueEx(PyObject
*self
, PyObject
*args
)
1245 if (!PyArg_ParseTuple(args
, "Oz:QueryValueEx", &obKey
, &valueName
))
1248 if (!PyHKEY_AsHKEY(obKey
, &hKey
, FALSE
))
1250 if ((rc
= RegQueryValueEx(hKey
, valueName
,
1254 return PyErr_SetFromWindowsErrWithFunction(rc
,
1256 retBuf
= (char *)alloca(bufSize
);
1257 if ((rc
= RegQueryValueEx(hKey
, valueName
, NULL
,
1258 &typ
, (BYTE
*)retBuf
, &bufSize
))
1260 return PyErr_SetFromWindowsErrWithFunction(rc
,
1262 obData
= Reg2Py(retBuf
, bufSize
, typ
);
1265 result
= Py_BuildValue("Oi", obData
, typ
);
1272 PySaveKey(PyObject
*self
, PyObject
*args
)
1277 LPSECURITY_ATTRIBUTES pSA
= NULL
;
1280 if (!PyArg_ParseTuple(args
, "Os:SaveKey", &obKey
, &fileName
))
1282 if (!PyHKEY_AsHKEY(obKey
, &hKey
, FALSE
))
1284 /* One day we may get security into the core?
1285 if (!PyWinObject_AsSECURITY_ATTRIBUTES(obSA, &pSA, TRUE))
1288 Py_BEGIN_ALLOW_THREADS
1289 rc
= RegSaveKey(hKey
, fileName
, pSA
);
1290 Py_END_ALLOW_THREADS
1291 if (rc
!= ERROR_SUCCESS
)
1292 return PyErr_SetFromWindowsErrWithFunction(rc
, "RegSaveKey");
1298 PySetValue(PyObject
*self
, PyObject
*args
)
1309 if (!PyArg_ParseTuple(args
, "OOiO:SetValue",
1315 if (!PyHKEY_AsHKEY(obKey
, &hKey
, FALSE
))
1317 if (typ
!= REG_SZ
) {
1318 PyErr_SetString(PyExc_TypeError
,
1319 "Type must be win32con.REG_SZ");
1322 /* XXX - need Unicode support */
1323 str
= PyString_AsString(obStrVal
);
1326 len
= PyString_Size(obStrVal
);
1327 if (obSubKey
== Py_None
)
1330 subKey
= PyString_AsString(obSubKey
);
1334 Py_BEGIN_ALLOW_THREADS
1335 rc
= RegSetValue(hKey
, subKey
, REG_SZ
, str
, len
+1);
1336 Py_END_ALLOW_THREADS
1337 if (rc
!= ERROR_SUCCESS
)
1338 return PyErr_SetFromWindowsErrWithFunction(rc
, "RegSetValue");
1344 PySetValueEx(PyObject
*self
, PyObject
*args
)
1357 if (!PyArg_ParseTuple(args
, "OzOiO:SetValueEx",
1364 if (!PyHKEY_AsHKEY(obKey
, &hKey
, FALSE
))
1366 if (!Py2Reg(value
, typ
, &data
, &len
))
1368 if (!PyErr_Occurred())
1369 PyErr_SetString(PyExc_ValueError
,
1370 "Could not convert the data to the specified type.");
1373 Py_BEGIN_ALLOW_THREADS
1374 rc
= RegSetValueEx(hKey
, valueName
, 0, typ
, data
, len
);
1375 Py_END_ALLOW_THREADS
1377 if (rc
!= ERROR_SUCCESS
)
1378 return PyErr_SetFromWindowsErrWithFunction(rc
,
1384 static struct PyMethodDef winreg_methods
[] = {
1385 {"CloseKey", PyCloseKey
, 1, CloseKey_doc
},
1386 {"ConnectRegistry", PyConnectRegistry
, 1, ConnectRegistry_doc
},
1387 {"CreateKey", PyCreateKey
, 1, CreateKey_doc
},
1388 {"DeleteKey", PyDeleteKey
, 1, DeleteKey_doc
},
1389 {"DeleteValue", PyDeleteValue
, 1, DeleteValue_doc
},
1390 {"EnumKey", PyEnumKey
, 1, EnumKey_doc
},
1391 {"EnumValue", PyEnumValue
, 1, EnumValue_doc
},
1392 {"FlushKey", PyFlushKey
, 1, FlushKey_doc
},
1393 {"LoadKey", PyLoadKey
, 1, LoadKey_doc
},
1394 {"OpenKey", PyOpenKey
, 1, OpenKey_doc
},
1395 {"OpenKeyEx", PyOpenKey
, 1, OpenKeyEx_doc
},
1396 {"QueryValue", PyQueryValue
, 1, QueryValue_doc
},
1397 {"QueryValueEx", PyQueryValueEx
, 1, QueryValueEx_doc
},
1398 {"QueryInfoKey", PyQueryInfoKey
, 1, QueryInfoKey_doc
},
1399 {"SaveKey", PySaveKey
, 1, SaveKey_doc
},
1400 {"SetValue", PySetValue
, 1, SetValue_doc
},
1401 {"SetValueEx", PySetValueEx
, 1, SetValueEx_doc
},
1406 insint(PyObject
* d
, char * name
, long value
)
1408 PyObject
*v
= PyInt_FromLong(value
);
1409 if (!v
|| PyDict_SetItemString(d
, name
, v
))
1414 #define ADD_INT(val) insint(d, #val, val)
1417 inskey(PyObject
* d
, char * name
, HKEY key
)
1419 PyObject
*v
= PyLong_FromVoidPtr(key
);
1420 if (!v
|| PyDict_SetItemString(d
, name
, v
))
1425 #define ADD_KEY(val) inskey(d, #val, val)
1427 __declspec(dllexport
) void init_winreg(void)
1430 m
= Py_InitModule3("_winreg", winreg_methods
, module_doc
);
1431 d
= PyModule_GetDict(m
);
1432 PyHKEY_Type
.ob_type
= &PyType_Type
;
1433 PyHKEY_Type
.tp_doc
= PyHKEY_doc
;
1434 Py_INCREF(&PyHKEY_Type
);
1435 if (PyDict_SetItemString(d
, "HKEYType",
1436 (PyObject
*)&PyHKEY_Type
) != 0)
1438 Py_INCREF(PyExc_WindowsError
);
1439 if (PyDict_SetItemString(d
, "error",
1440 PyExc_WindowsError
) != 0)
1443 /* Add the relevant constants */
1444 ADD_KEY(HKEY_CLASSES_ROOT
);
1445 ADD_KEY(HKEY_CURRENT_USER
);
1446 ADD_KEY(HKEY_LOCAL_MACHINE
);
1447 ADD_KEY(HKEY_USERS
);
1448 ADD_KEY(HKEY_PERFORMANCE_DATA
);
1449 #ifdef HKEY_CURRENT_CONFIG
1450 ADD_KEY(HKEY_CURRENT_CONFIG
);
1452 #ifdef HKEY_DYN_DATA
1453 ADD_KEY(HKEY_DYN_DATA
);
1455 ADD_INT(KEY_QUERY_VALUE
);
1456 ADD_INT(KEY_SET_VALUE
);
1457 ADD_INT(KEY_CREATE_SUB_KEY
);
1458 ADD_INT(KEY_ENUMERATE_SUB_KEYS
);
1459 ADD_INT(KEY_NOTIFY
);
1460 ADD_INT(KEY_CREATE_LINK
);
1463 ADD_INT(KEY_EXECUTE
);
1464 ADD_INT(KEY_ALL_ACCESS
);
1465 ADD_INT(REG_OPTION_RESERVED
);
1466 ADD_INT(REG_OPTION_NON_VOLATILE
);
1467 ADD_INT(REG_OPTION_VOLATILE
);
1468 ADD_INT(REG_OPTION_CREATE_LINK
);
1469 ADD_INT(REG_OPTION_BACKUP_RESTORE
);
1470 ADD_INT(REG_OPTION_OPEN_LINK
);
1471 ADD_INT(REG_LEGAL_OPTION
);
1472 ADD_INT(REG_CREATED_NEW_KEY
);
1473 ADD_INT(REG_OPENED_EXISTING_KEY
);
1474 ADD_INT(REG_WHOLE_HIVE_VOLATILE
);
1475 ADD_INT(REG_REFRESH_HIVE
);
1476 ADD_INT(REG_NO_LAZY_FLUSH
);
1477 ADD_INT(REG_NOTIFY_CHANGE_NAME
);
1478 ADD_INT(REG_NOTIFY_CHANGE_ATTRIBUTES
);
1479 ADD_INT(REG_NOTIFY_CHANGE_LAST_SET
);
1480 ADD_INT(REG_NOTIFY_CHANGE_SECURITY
);
1481 ADD_INT(REG_LEGAL_CHANGE_FILTER
);
1484 ADD_INT(REG_EXPAND_SZ
);
1485 ADD_INT(REG_BINARY
);
1487 ADD_INT(REG_DWORD_LITTLE_ENDIAN
);
1488 ADD_INT(REG_DWORD_BIG_ENDIAN
);
1490 ADD_INT(REG_MULTI_SZ
);
1491 ADD_INT(REG_RESOURCE_LIST
);
1492 ADD_INT(REG_FULL_RESOURCE_DESCRIPTOR
);
1493 ADD_INT(REG_RESOURCE_REQUIREMENTS_LIST
);