Automated tests on Windows often have access to read and write operations on the registry, for example, to get a program's installation directory, in general, we can go to the registry app paths down to find, this involves the registry read operations, we use the python _ WinReg module to implement the code as follows:
def reg_query (Path, key): try: path = Path.replace ("/", "\ \") Rootname = path[:p ath.find ("\ \")] Subpath = Path[path.find ("\ \") + 1:] Rootkey = _query_root (rootname) if Rootkey is None: return "" print Path root = _winreg. Openkey (Rootkey, subpath) value, type = _winreg. QueryValueEx (Root, key) return value except: # log.exception (Traceback.format_exc ()) return ""
Where the _query_root method is to get root enumeration values according to Rootname, the code is as follows:
def _query_root (rootname): rootkey = None if rootname = = "HKEY_LOCAL_MACHINE": Rootkey = _winreg. HKEY_LOCAL_MACHINE Elif Rootname = = "HKEY_CLASSES_ROOT": rootkey = _winreg. HKEY_CLASSES_ROOT elif rootname = = "HKEY_CURRENT_USER": Rootkey = _winreg. HKEY_CURRENT_USER elif Rootname = = "HKEY_USERS": rootkey = _winreg. HKEY_USERS elif Rootname = = "Hkey_current_config": rootkey = _winreg. Hkey_current_config return Rootkey
So how do we use it? Use the following method to get the path of Python:
PythonPath = Reg_query (r "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\python.exe", "")
Read operation completed, in some cases, in order to modify some environment or program configuration in the test, we need to write to the registry, look at the code
def req_add (path, key, value, Type=_winreg. REG_SZ): try: path = Path.replace ("/", "\ \") Rootname = path[:p ath.find ("\ \")] subpath = path[ Path.find ("\ \") + 1:] Rootkey = _query_root (rootname) if Rootkey is None: return "" print path root = _winreg. Openkey (Rootkey, subpath, 0, _winreg. key_all_access) # subkey = _winreg. Createkeyex (Root, key) _winreg. SetValueEx (root, key, 0, type, value) return True except: log.exception (Traceback.format_exc ()) return False
The usage is also relatively simple, for example, we want to add an option value under the Python path, as follows:
Reg_add (r "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\python.exe", "Test", "test")
Reprint Please specify: Http://blog.csdn.net/sogouauto
Explore test art, Exchange test technology, Welcome to the "Sogou test"
Python writes automated registry read and write operations