Open key in Win32 registry base like a file. All commands supported by StringIO are available.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 | import win32con
# Definition des clef de registre
HKEY_CLASSES_ROOT = win32con.HKEY_CLASSES_ROOT
HKEY_CURRENT_USER = win32con.HKEY_CURRENT_USER
HKEY_LOCAL_MACHINE = win32con.HKEY_LOCAL_MACHINE
HKEY_USERS = win32con.HKEY_USERS
class RegistryFileError(Exception):
def __init__(self):
Exception.__init__(self)
class FileNotFoundError(RegistryFileError):
""" File not found error """
def __init__(self,key,sub_key):
RegistryFileError.__init__(self)
self.key = key
self.sub_key = sub_key
def __str__(self):
return 'No such registry file or directory %X:%s'%(self.key,self.sub_key)
class InvalidModeError(RegistryFileError):
""" Invalid mode error ou mode unknown """
def __init__(self, flag):
RegistryFileError.__init__(self)
self.flag = flag
def __str__(self):
return 'Invalid mode: %s'%self.flag
class BadFileDescriptorError(RegistryFileError):
""" The cannot be read or write according to mode """
def __init__(self):
RegistryFileError.__init__(self)
def __str__(self):
return 'Bad registry file descriptor'
class RegistryFile:
""" This class manage a file in a Win32 registry base """
READ = 1
WRITE = 2
APPEND = 3
def __init__(self, key, sub_key, flag):
"""
Constructor :
key : HKEY_CLASSES_ROOT, HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE, HKEY_USERS
sub_key : The name of a key that this method opens
flag : "r" for read
"w" for write
"a" for append
"b" for binary
"""
from win32api import RegQueryValueEx, RegCreateKey, RegOpenKeyEx
from win32con import KEY_ALL_ACCESS
from StringIO import StringIO
# Save files informations
self.key = key
self.sub_key = sub_key
# Initialization of internal data
self.deleted = 0
self.handle = None
self.data = None
# Check mode
self.__checkMode(flag)
# Create an empty file
self.data = StringIO()
try:
# Open registry key
self.handle = RegOpenKeyEx(key,sub_key,0,KEY_ALL_ACCESS)
# Read key content
data = RegQueryValueEx(self.handle, "")[0]
# If the file is in read mode
if self.flag == self.READ:
# Read data
self.data = StringIO(data)
# If the file is in append mode
elif self.flag == self.APPEND:
self.data.write (data)
except: # If the registry key not found
# If the file must be read
if self.flag == self.READ:
# The file is not found
raise FileNotFoundError(key,sub_key)
else:
# Create a new registry key
self.handle = RegCreateKey(key, sub_key)
def __del__(self):
""" Destructor """
self.close()
def __checkMode(self, flag):
""" Check the file mode """
from string import lower
self.binary = 0
for i in flag:
try:
# Obtain flag
self.flag = {"r":self.READ,"w":self.WRITE,"a":self.APPEND}[lower(i)]
except:
# If binary file selected
if lower(i) == "b":
# Set binary file
self.binary = 1
else:
# Invalid mode
raise InvalidModeError(flag)
def __checkRead(self):
""" Check if the file can be read """
if self.flag != self.READ:
raise BadFileDescriptorError
def __checkWrite(self):
""" Check if the file can be writed """
if not self.flag in (self.WRITE,self.APPEND):
raise BadFileDescriptorError
def close(self):
""" Close file and write in registry """
from win32con import REG_SZ, REG_BINARY
from win32api import RegSetValueEx
# If the file has been opened correctly
if self.handle != None and self.data != None:
# If the file has not been deleted
if self.deleted == 0:
# If the file is opened with binary mode
if self.binary:
typ = REG_BINARY
else:
typ = REG_SZ
# Write data in registry base
RegSetValueEx (self.handle, "", 0, typ, self.data.getvalue())
# Close file
result = self.data.close()
self.data = None
return result
def delete(self):
""" Delete the registry file """
from win32api import RegDeleteKey
# Destroy file
RegDeleteKey(self.key, self.sub_key)
self.deleted = 1
def isatty(self):
return self.data.isatty()
def seek(self, pos, mode = 0):
return self.seek(pos, mode)
def tell(self):
return self.data.tell()
def read(self, size = -1):
self.__checkRead()
return self.data.read(size)
def readline(self, length=None):
self.__checkRead()
return self.data.readline(length)
def readlines(self, sizehint = 0):
self.__checkRead()
return self.data.readlines(sizehint)
def truncate(self, size=None):
self.__checkWrite()
return self.data.truncate(size)
def write(self, s):
self.__checkWrite()
return self.data.write(s)
def writelines(self, list):
self.__checkWrite()
return self.data.writelines(list)
def flush(self):
self.__checkWrite()
return self.data.flush()
import unittest
class RegistryFileTest(unittest.TestCase):
def testFileNotFoundError(self):
self.assertRaises(FileNotFoundError, RegistryFile, HKEY_LOCAL_MACHINE,"Software\\NotFound","r")
def testInvalidModeError(self):
self.assertRaises(InvalidModeError, RegistryFile, HKEY_LOCAL_MACHINE,"Software\\NotFound","z")
def testWriteNormalFile(self):
from time import sleep
RegistryFile(HKEY_LOCAL_MACHINE,"Software\\RegistryFileTest","w").write("toto\0")
self.assertEqual(RegistryFile(HKEY_LOCAL_MACHINE,"Software\\RegistryFileTest","r").read(),"toto")
def testWriteBinaryFile(self):
RegistryFile(HKEY_LOCAL_MACHINE,"Software\\RegistryFileTest","wb").write("toto\0")
self.assertEqual(RegistryFile(HKEY_LOCAL_MACHINE,"Software\\RegistryFileTest","rb").read(),"toto\0")
def testWriteAllBinaryCode(self):
buf = ""
for i in range(0,256):
buf += chr(i%256)
RegistryFile(HKEY_LOCAL_MACHINE,"Software\\RegistryFileTest","wb").write(buf)
self.assertEqual(RegistryFile(HKEY_LOCAL_MACHINE,"Software\\RegistryFileTest","rb").read(),buf)
def testWriteReadLines(self):
buf = ["Line1\n","Line2\n","Line3\n"]
RegistryFile(HKEY_LOCAL_MACHINE,"Software\\RegistryFileTest","w").writelines(buf)
self.assertEqual(RegistryFile(HKEY_LOCAL_MACHINE,"Software\\RegistryFileTest","r").readlines(),buf)
def testZDeleteFile(self):
RegistryFile(HKEY_LOCAL_MACHINE,"Software\\RegistryFileTest","r").delete()
self.assertRaises(FileNotFoundError, RegistryFile, HKEY_LOCAL_MACHINE,"Software\\RegistryFileTest","r")
def sample():
file = RegistryFile(HKEY_LOCAL_MACHINE,"Software\\RegistryFileTest","w")
file.write ("Hello world")
del(file)
file = RegistryFile(HKEY_LOCAL_MACHINE,"Software\\RegistryFileTest","r")
print file.read()
file.delete()
if __name__ == "__main__":
sample()
unittest.main()
|
Open key in Win32 registry base like a file. All commands supported by StringIO are available : isatty,seek,tell,read,readline,readlines,truncate,write,writelines,flush.
Exceptions : RegistryFileError : All exceptions. FileNotFoundError : File not found. InvalidModeError : Invalid mode error (not in "r","a","w","rb","ab","wb"). BadFileDescriptorError : Bad file descriptor (write with file open in read mode).
Sample : import RegistryFile # Open and create the key "HKEY_LOCAL_MACHINE\Software\RegistryFileTest" file = RegistryFile.RegistryFile(HKEY_LOCAL_MACHINE,"Software\RegistryFileTest","w") # Write data file.write ("Hello world") # Destroy file (write file in registry base) del(file)
# Open key in read mode file = RegistryFile.RegistryFile(HKEY_LOCAL_MACHINE,"Software\RegistryFileTest","r") # Read and display data stored print file.read() # Delete registry key file.delete()
Requirement: - win32con library
Author: remi_inconnu@yahoo.fr