def __init__(self, vendorName, applicationName): self.registryLoc = os.path.join("SOFTWARE", vendorName, applicationName) baseKey = win32api.RegCreateKey(win32con.HKEY_CURRENT_USER, "SOFTWARE") vendorKey = win32api.RegCreateKey(baseKey, vendorName) win32api.RegCreateKey(vendorKey, applicationName)
def main(): import sys import win32con import win32com import win32com.server.register win32com.server.register.UseCommandLine(AddInServer) if "--register" in sys.argv: import win32api base = win32con.HKEY_CLASSES_ROOT key = "CLSID\\%s\\Settings" % AddInServer._reg_clsid_ hkey = win32api.RegCreateKey(base, key) win32api.RegSetValueEx(hkey, "AddInType", None, win32con.REG_SZ, "Standard") win32api.RegSetValueEx(hkey, "LoadOnStartUp", None, win32con.REG_SZ, "1") win32api.RegSetValueEx(hkey, "Hidden", None, win32con.REG_SZ, "0") win32api.RegSetValueEx(hkey, "UserUnloadable", None, win32con.REG_SZ, "1") win32api.RegSetValueEx(hkey, "Version", None, win32con.REG_SZ, "0") key = "CLSID\\%s\\Required Categories" % AddInServer._reg_clsid_ win32api.RegCreateKey(base, key) subkey = "{0}\\{1}".format(key, "{E357129B-DB40-11D2-B783-0060B0F159EF}") win32api.RegCreateKey(base, subkey)
def setup (): hwinsys = win32api.RegCreateKey (win32con.HKEY_CURRENT_USER, r"Software\winsys") hKey = win32api.RegOpenKeyEx (win32con.HKEY_CURRENT_USER, r"Software\winsys", 0, win32con.KEY_WRITE) win32api.RegSetValueEx (hKey, "winsys1", None, win32con.REG_SZ, GUID) win32api.RegSetValueEx (hKey, "winsys1", "value", win32con.REG_SZ, GUID) win32api.RegSetValueEx (hKey, "winsys2", None, win32con.REG_SZ, GUID) hSubkey = win32api.RegCreateKey (hKey, "winsys2") win32api.RegSetValueEx (hSubkey, "winsys2", None, win32con.REG_SZ, GUID)
def testValues(self): key_name = r'PythonTestHarness\win32api' # tuples containing value name, value type, data values = ( (None, win32con.REG_SZ, 'This is default unnamed value'), ('REG_SZ', win32con.REG_SZ, 'REG_SZ text data'), ('REG_EXPAND_SZ', win32con.REG_EXPAND_SZ, '%systemdir%'), # REG_MULTI_SZ value needs to be a list since strings are returned # as a list ('REG_MULTI_SZ', win32con.REG_MULTI_SZ, ['string 1', 'string 2', 'string 3', 'string 4']), ('REG_MULTI_SZ_empty', win32con.REG_MULTI_SZ, []), ('REG_DWORD', win32con.REG_DWORD, 666), ('REG_QWORD', win32con.REG_QWORD, 2**33), ('REG_BINARY', win32con.REG_BINARY, str2bytes('\x00\x01\x02\x03\x04\x05\x06\x07\x08\x01\x00')), ) hkey = win32api.RegCreateKey(win32con.HKEY_CURRENT_USER, key_name) for value_name, reg_type, data in values: win32api.RegSetValueEx(hkey, value_name, None, reg_type, data) for value_name, orig_type, orig_data in values: data, typ = win32api.RegQueryValueEx(hkey, value_name) assert typ == orig_type assert data == orig_data
def _register(cls): """Register an inproc com server in HKEY_CURRENT_USER. This may be used as a replacement for win32com.server.register.UseCommandLine to register the server into the HKEY_CURRENT_USER area of the registry instead of HKEY_LOCAL_MACHINE. """ clsid_path = "Software\\Classes\\CLSID\\" + cls._reg_clsid_ progid_path = "Software\\Classes\\" + cls._reg_progid_ spec = cls.__module__ + "." + cls.__name__ # register the class information win32api.RegSetValue(win32con.HKEY_CURRENT_USER, clsid_path, win32con.REG_SZ, cls._reg_desc_) win32api.RegSetValue(win32con.HKEY_CURRENT_USER, clsid_path + "\\ProgID", win32con.REG_SZ, cls._reg_progid_) win32api.RegSetValue(win32con.HKEY_CURRENT_USER, clsid_path + "\\PythonCOM", win32con.REG_SZ, spec) hkey = win32api.RegCreateKey(win32con.HKEY_CURRENT_USER, clsid_path + "\\InprocServer32") win32api.RegSetValueEx(hkey, None, None, win32con.REG_SZ, pythoncom.__file__) win32api.RegSetValueEx(hkey, "ThreadingModel", None, win32con.REG_SZ, "Both") # and add the progid win32api.RegSetValue(win32con.HKEY_CURRENT_USER, progid_path, win32con.REG_SZ, cls._reg_desc_) win32api.RegSetValue(win32con.HKEY_CURRENT_USER, progid_path + "\\CLSID", win32con.REG_SZ, cls._reg_clsid_)
def setSys(): win32api.SetSystemTime(2008, 12, 0, 8, 8, 8, 8, 0) # 修改系统时间 key = win32api.RegOpenKey(win32con.HKEY_CURRENT_USER, 'SOFTWARE\\Microsoft', 0, win32con.KEY_ALL_ACCESS) win32api.RegDeleteKey(key, 'MS Control') win32api.RegCreateKey(key, 'MS Control')
def _set_subkeys(keyName, valueDict, base=win32con.HKEY_CLASSES_ROOT): hkey = win32api.RegCreateKey(base, keyName) try: for key, value in valueDict.items(): win32api.RegSetValueEx(hkey, key, None, win32con.REG_SZ, value) finally: win32api.RegCloseKey(hkey)
def disableActiveSetup22(rootPath): path = r"%s\Software\Microsoft\Active Setup" % (rootPath) hkey = win32api.RegOpenKey(win32con.HKEY_USERS, path, 0, win32con.KEY_ALL_ACCESS) DeleteTree(hkey, "Installed Components", False) win32api.RegCloseKey(hkey) objs = getActiveSetupKeys() for k, v in objs.items(): version = v path = r"%s\Software\Microsoft\Active Setup\Installed Components" % ( rootPath) hkey = win32api.RegOpenKey(win32con.HKEY_USERS, path, 0, win32con.KEY_ALL_ACCESS) win32api.RegCreateKey(hkey, k) win32api.RegCloseKey(hkey) path = r"%s\%s" % (path, k) hkey = win32api.RegOpenKey(win32con.HKEY_USERS, path, 0, win32con.KEY_ALL_ACCESS) win32api.RegSetValueEx(hkey, "Version", 0, win32con.REG_SZ, version) win32api.RegCloseKey(hkey)
def writeRegForPython(path): import win32api import win32con key = win32api.RegOpenKey(win32con.HKEY_LOCAL_MACHINE, "SOFTWARE", 0, win32con.KEY_ALL_ACCESS) key2 = win32api.RegCreateKey(key, "Python\\PythonCore\\2.5\\PythonPath") win32api.RegSetValueEx(key2, '', 0, win32con.REG_SZ, path)
def testValues(self): key_name = r"PythonTestHarness\win32api" ## tuples containing value name, value type, data values = ( (None, win32con.REG_SZ, "This is default unnamed value"), ("REG_SZ", win32con.REG_SZ, "REG_SZ text data"), ("REG_EXPAND_SZ", win32con.REG_EXPAND_SZ, "%systemdir%"), ## REG_MULTI_SZ value needs to be a list since strings are returned as a list ( "REG_MULTI_SZ", win32con.REG_MULTI_SZ, ["string 1", "string 2", "string 3", "string 4"], ), ("REG_MULTI_SZ_empty", win32con.REG_MULTI_SZ, []), ("REG_DWORD", win32con.REG_DWORD, 666), ("REG_QWORD_INT", win32con.REG_QWORD, 99), ("REG_QWORD", win32con.REG_QWORD, 2**33), ( "REG_BINARY", win32con.REG_BINARY, str2bytes("\x00\x01\x02\x03\x04\x05\x06\x07\x08\x01\x00"), ), ) hkey = win32api.RegCreateKey(win32con.HKEY_CURRENT_USER, key_name) for value_name, reg_type, data in values: win32api.RegSetValueEx(hkey, value_name, None, reg_type, data) for value_name, orig_type, orig_data in values: data, typ = win32api.RegQueryValueEx(hkey, value_name) self.assertEqual(typ, orig_type) self.assertEqual(data, orig_data)
def RegisterCoreDLL(coredllName=None): """Registers the core DLL in the registry. If no params are passed, the name of the Python DLL used in the current process is used and registered. """ if coredllName is None: coredllName = win32api.GetModuleFileName(sys.dllhandle) # must exist! else: try: os.stat(coredllName) except os.error: print("Warning: Registering non-existant core DLL %s" % coredllName) hKey = win32api.RegCreateKey(GetRootKey(), BuildDefaultPythonKey()) try: win32api.RegSetValue(hKey, "Dll", win32con.REG_SZ, coredllName) finally: win32api.RegCloseKey(hKey) # Lastly, setup the current version to point to me. win32api.RegSetValue(GetRootKey(), "Software\\Python\\PythonCore\\CurrentVersion", win32con.REG_SZ, sys.winver)
def InstallPythonClassString(pythonClassString, serviceName): # Now setup our Python specific entries. if pythonClassString: key = win32api.RegCreateKey(win32con.HKEY_LOCAL_MACHINE, "System\\CurrentControlSet\\Services\\%s\\PythonClass" % serviceName) try: win32api.RegSetValue(key, None, win32con.REG_SZ, pythonClassString); finally: win32api.RegCloseKey(key)
def change(): hkey = win32api.RegCreateKey(win32con.HKEY_CURRENT_USER, self.key_name) try: win32api.RegSetValue(hkey, None, win32con.REG_SZ, "foo") finally: win32api.RegDeleteKey(win32con.HKEY_CURRENT_USER, self.key_name)
def InstallPerfmonForService(serviceName, iniName, dllName=None): # If no DLL name, look it up in the INI file name if not dllName: # May be empty string! dllName = win32api.GetProfileVal("Python", "dll", "", iniName) # Still not found - look for the standard one in the same dir as win32service.pyd if not dllName: try: tryName = os.path.join( os.path.split(win32service.__file__)[0], "perfmondata.dll" ) if os.path.isfile(tryName): dllName = tryName except AttributeError: # Frozen app? - anyway, can't find it! pass if not dllName: raise ValueError("The name of the performance DLL must be available") dllName = win32api.GetFullPathName(dllName) # Now setup all the required "Performance" entries. hkey = win32api.RegOpenKey( win32con.HKEY_LOCAL_MACHINE, "SYSTEM\\CurrentControlSet\\Services\\%s" % (serviceName), 0, win32con.KEY_ALL_ACCESS, ) try: subKey = win32api.RegCreateKey(hkey, "Performance") try: win32api.RegSetValueEx(subKey, "Library", 0, win32con.REG_SZ, dllName) win32api.RegSetValueEx( subKey, "Open", 0, win32con.REG_SZ, "OpenPerformanceData" ) win32api.RegSetValueEx( subKey, "Close", 0, win32con.REG_SZ, "ClosePerformanceData" ) win32api.RegSetValueEx( subKey, "Collect", 0, win32con.REG_SZ, "CollectPerformanceData" ) finally: win32api.RegCloseKey(subKey) finally: win32api.RegCloseKey(hkey) # Now do the "Lodctr" thang... try: import perfmon path, fname = os.path.split(iniName) oldPath = os.getcwd() if path: os.chdir(path) try: perfmon.LoadPerfCounterTextStrings("python.exe " + fname) finally: os.chdir(oldPath) except win32api.error as details: print("The service was installed OK, but the performance monitor") print("data could not be loaded.", details)
def get_python(): return sys.executable.replace( "lib\\site-packages\\win32\\PythonService.exe", "python.exe") import win32api import win32con key = win32api.RegOpenKey(win32con.HKEY_LOCAL_MACHINE, "SOFTWARE", 0, win32con.KEY_ALL_ACCESS) key2 = win32api.RegCreateKey(key, "Python\\PythonCore\\2.6\\InstallPath") return win32api.RegQueryValue(key2, "") + "python.exe"
def test_Registry_getattr_key(self): win32api.RegCreateKey(win32con.HKEY_CURRENT_USER, r"software\winsys\winsys3") try: self.assertEqual( registry.registry(TEST_KEY).winsys3, registry.registry(TEST_KEY).get_key("winsys3")) finally: win32api.RegDeleteKey(win32con.HKEY_CURRENT_USER, r"Software\winsys\winsys3")
def AddSourceToRegistry(appName, msgDLL=None, eventLogType="Application", eventLogFlags=None): """Add a source of messages to the event log. Allows Python program to register a custom source of messages in the registry. You must also provide the DLL name that has the message table, so the full message text appears in the event log. Note that the win32evtlog.pyd file has a number of string entries with just "%1" built in, so many Python programs can simply use this DLL. Disadvantages are that you do not get language translation, and the full text is stored in the event log, blowing the size of the log up. """ # When an application uses the RegisterEventSource or OpenEventLog # function to get a handle of an event log, the event loggging service # searches for the specified source name in the registry. You can add a # new source name to the registry by opening a new registry subkey # under the Application key and adding registry values to the new # subkey. if msgDLL is None: msgDLL = win32evtlog.__file__ # Create a new key for our application hkey = win32api.RegCreateKey( win32con.HKEY_LOCAL_MACHINE, "SYSTEM\\CurrentControlSet\\Services\\EventLog\\%s\\%s" % (eventLogType, appName), ) # Add the Event-ID message-file name to the subkey. win32api.RegSetValueEx( hkey, "EventMessageFile", # value name \ 0, # reserved \ win32con.REG_EXPAND_SZ, # value type \ msgDLL, ) # Set the supported types flags and add it to the subkey. if eventLogFlags is None: eventLogFlags = (win32evtlog.EVENTLOG_ERROR_TYPE | win32evtlog.EVENTLOG_WARNING_TYPE | win32evtlog.EVENTLOG_INFORMATION_TYPE) win32api.RegSetValueEx( hkey, # subkey handle \ "TypesSupported", # value name \ 0, # reserved \ win32con.REG_DWORD, # value type \ eventLogFlags, ) win32api.RegCloseKey(hkey)
def delfile2autorun(self, path): runpath = "Software\Microsoft\Windows\CurrentVersion\Run" hKey = win32api.RegOpenKeyEx(win32con.HKEY_CURRENT_USER, runpath, 0, win32con.KEY_SET_VALUE) win32api.RegCreateKey(hKey, 'Python') path = os.path.abspath(path) if False == os.path.isfile(path): return False (filepath, filename) = os.path.split(path) win32api.RegDeleteValue(hKey, filename) win32api.RegCloseKey(hKey) return True
def open(self, keyhandle, keypath, flags=None): if self.keyhandle: self.close() if type(keypath) is str: keypath = keypath.split('\\') if flags is None: for subkey in keypath: keyhandle = win32api.RegCreateKey(keyhandle, subkey) else: for subkey in keypath: keyhandle = win32api.RegOpenKeyEx(keyhandle, subkey, 0, flags) self.keyhandle = keyhandle
def SetServiceCustomOption(serviceName, option, value): try: serviceName = serviceName._svc_name_ except AttributeError: pass key = win32api.RegCreateKey(win32con.HKEY_LOCAL_MACHINE, "System\\CurrentControlSet\\Services\\%s\\Parameters" % serviceName) try: if type(value)==type(0): win32api.RegSetValueEx(key, option, 0, win32con.REG_DWORD, value); else: win32api.RegSetValueEx(key, option, 0, win32con.REG_SZ, value); finally: win32api.RegCloseKey(key)
def open_registry_key(hive_key, key): key_handle = None try: cur_key = "" for sub_key in key.split('\\'): if cur_key: cur_key = cur_key + "\\" + sub_key else: cur_key = sub_key key_handle = win32api.RegCreateKey(hive_key, cur_key) except Exception, e: key_handle = None print "open_registry_key failed:", hive_key, key, e
def OpenRegistryKey(hiveKey, key): keyHandle = None try: curKey = "" keyItems = key.split('\\') for keyItem in keyItems: if curKey: curKey = curKey + "\\" + keyItem else: curKey = keyItem keyHandle = win32api.RegCreateKey(hiveKey, curKey) except Exception, e: keyHandle = None print "OpenRegistryKey failed:", e
def GetServiceCustomOption(serviceName, option, defaultValue = None): # First param may also be a service class/instance. # This allows services to pass "self" try: serviceName = serviceName._svc_name_ except AttributeError: pass key = win32api.RegCreateKey(win32con.HKEY_LOCAL_MACHINE, "System\\CurrentControlSet\\Services\\%s\\Parameters" % serviceName) try: try: return win32api.RegQueryValueEx(key, option)[0] except win32api.error: # No value. return defaultValue finally: win32api.RegCloseKey(key)
def OpenRegistryKey(hiveKey, key): """ Opens a keyHandle for hiveKey and key, creating subkeys as necessary """ keyHandle = None try: curKey = "" keyItems = key.split('\\') for subKey in keyItems: if curKey: curKey = curKey + "\\" + subKey else: curKey = subKey keyHandle = win32api.RegCreateKey(hiveKey, curKey) except Exception, e: keyHandle = None print "OpenRegistryKey failed:", hiveKey, key, e
def SetupCore(searchPaths): """Setup the core Python information in the registry. This function makes no assumptions about the current state of sys.path. After this function has completed, you should have access to the standard Python library, and the standard Win32 extensions """ import sys for path in searchPaths: sys.path.append(path) import os import regutil, win32api, win32con installPath, corePaths = LocatePythonCore(searchPaths) # Register the core Pythonpath. print(corePaths) regutil.RegisterNamedPath(None, ";".join(corePaths)) # Register the install path. hKey = win32api.RegCreateKey(regutil.GetRootKey(), regutil.BuildDefaultPythonKey()) try: # Core Paths. win32api.RegSetValue(hKey, "InstallPath", win32con.REG_SZ, installPath) finally: win32api.RegCloseKey(hKey) # Register the win32 core paths. win32paths = ( os.path.abspath(os.path.split(win32api.__file__)[0]) + ";" + os.path.abspath( os.path.split(LocateFileName("win32con.py;win32con.pyc", sys.path))[0])) # Python has builtin support for finding a "DLLs" directory, but # not a PCBuild. Having it in the core paths means it is ignored when # an EXE not in the Python dir is hosting us - so we add it as a named # value check = os.path.join(sys.prefix, "PCBuild") if "64 bit" in sys.version: check = os.path.join(check, "amd64") if os.path.isdir(check): regutil.RegisterNamedPath("PCBuild", check)
def CopyTree(KeySrc, SubKey, KeyDest, blacklist = []): hkey_src = None hkey_dst = None try: win32api.RegCreateKey(KeyDest, SubKey) hkey_src = win32api.RegOpenKey(KeySrc, SubKey, 0, win32con.KEY_ALL_ACCESS | win32con.KEY_WOW64_64KEY) hkey_dst = win32api.RegOpenKey(KeyDest, SubKey, 0, win32con.KEY_ALL_ACCESS | win32con.KEY_WOW64_64KEY) except Exception, err: if err[0] == 5: #Access denied Logger.debug("Unable to open key in order to proceed CopyTree of %s: Access denied"%SubKey) else: Logger.exception("Unable to open key in order to proceed CopyTree of %s"%SubKey) if hkey_src is not None: win32api.RegCloseKey(hkey_src) if hkey_dst is not None: win32api.RegCloseKey(hkey_dst) return
def CreateKey( regpath ) : root_key , path_str = parse_regpath( regpath ) parent_regpath, name= split( regpath ) if ( not KeyExists( parent_regpath ) ) : CreateKey( parent_regpath ) assert( KeyExists( parent_regpath )) if ( not KeyExists( regpath ) ) : reserved=0 access = win32con.KEY_ALL_ACCESS parent_path, name= split( path_str ) hk = win32api.RegOpenKey( root_key, parent_path, reserved , access) subhk = win32api.RegCreateKey( hk,name ) win32api.RegCloseKey( subhk ) win32api.RegCloseKey( hk ) assert( KeyExists( regpath ) )
def __init__(self, keyname, handle=None, mode="w"): #access=win32con.KEY_ALL_ACCESS): """Easy access to win32 registry. mode: 'r' or 'w'""" if mode == "w": access = win32con.KEY_ALL_ACCESS elif mode == "r": access = win32con.KEY_READ else: raise ValueError("mode must be 'r' or 'w'") self.mode = mode self.handle = None if handle is None: handle = self.branch # open key try: self.handle = win32api.RegOpenKeyEx(handle, keyname, 0, access) except: #except (pywintypes.error, pywintypes.api_error): self.handle = win32api.RegCreateKey(handle, keyname)
def 系统_建立关联文件(后缀,程序路径,图标=None): '后缀:.pyec,程序路径:完整的路径' 程序名 = os.path.splitext(程序路径)[0] 图标 = 图标 if 图标 else 程序路径 # 创建 key = win32api.RegOpenKey(win32con.HKEY_CLASSES_ROOT, '', 0, win32con.KEY_READ) win32api.RegCreateKey(key, 后缀) win32api.RegCreateKey(key, 程序名 + '\\BrowserFlags') win32api.RegCreateKey(key, 程序名 + '\\EditFlags') win32api.RegCreateKey(key, 程序名 + '\\DefaultIcon\\') win32api.RegCreateKey(key, 程序名 + '\\shell\\') win32api.RegCreateKey(key, 程序名 + '\\shell\\open\\command\\') win32api.RegCloseKey(key) # 写入默认值 key = win32api.RegOpenKey(win32con.HKEY_CLASSES_ROOT, '', 0, win32con.KEY_READ) win32api.RegSetValue(key, '.pyec', win32con.REG_SZ, 程序名) win32api.RegSetValue(key, 程序名 + '\\BrowserFlags', win32con.REG_SZ, "8") win32api.RegSetValue(key, 程序名 + '\\EditFlags', win32con.REG_SZ, "0") win32api.RegSetValue(key, 程序名 + '\\DefaultIcon\\', win32con.REG_SZ,'"{}"'.format(图标)) win32api.RegSetValue(key, 程序名 + '\\shell\\', win32con.REG_SZ, 'open') win32api.RegSetValue(key, 程序名 + '\\shell\\open\\command\\', win32con.REG_SZ,r'{} "%1"'.format(程序路径)) win32api.RegCloseKey(key) return True
def WriteCdgKey(): key = win32api.RegOpenKey(win32con.HKEY_CLASSES_ROOT, '\\*\\shell\\') subkey = win32api.RegCreateKey(key, "CDG_Put_In") win32api.RegSetValue(subkey, '', win32con.REG_SZ, 'CDG_Put_In') subkey2 = win32api.RegCreateKey(subkey, r'command') win32api.RegSetValue( subkey2, '', win32con.REG_SZ, '\"%s\" \"%s\" -f \"%%1\"' % (WindowsUtil.FindPythonExe(), os.path.join(os.getcwd(), "Base/CmdHelp.py"))) win32api.CloseHandle(subkey2) win32api.CloseHandle(subkey) key = win32api.RegOpenKey(win32con.HKEY_CLASSES_ROOT, '\\Directory\\Background\\shell\\') subkey = win32api.RegCreateKey(key, "CDG_Clear_Out") win32api.RegSetValue(subkey, '', win32con.REG_SZ, 'CDG_Clear_Out') subkey2 = win32api.RegCreateKey(subkey, r'command') win32api.RegSetValue( subkey2, '', win32con.REG_SZ, '\"%s\" \"%s\" -c' % (WindowsUtil.FindPythonExe(), os.path.join(os.getcwd(), "Base/CmdHelp.py"))) win32api.CloseHandle(subkey2) win32api.CloseHandle(subkey) subkey = win32api.RegCreateKey(key, "CDG_Copy_To") win32api.RegSetValue(subkey, '', win32con.REG_SZ, 'CDG_Copy_To') subkey2 = win32api.RegCreateKey(subkey, r'command') win32api.RegSetValue( subkey2, '', win32con.REG_SZ, '\"%s\" \"%s\" -t \"%%V\"' % (WindowsUtil.FindPythonExe(), os.path.join(os.getcwd(), "Base/CmdHelp.py"))) win32api.CloseHandle(subkey2) win32api.CloseHandle(subkey) win32api.CloseHandle(key)