Windows上的自動化測試經常會接觸到對於註冊表的讀寫操作問題,比如,獲取一個程序的安裝目錄,一般情況下,我們可以去註冊表的App Paths下去查找,這時就涉及到了註冊表的讀取操作,我們使用Python的_winreg模塊來實現,代碼如下:
def reg_query(path, key):
try:
path = path.replace("/", "\\")
rootName = path[:path.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 ""
其中_query_root方法,是根據rootName去獲取Root的枚舉值,代碼如下:
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
那我們如何使用呢?使用方式如下,獲取Python的路徑:
pythonPath = reg_query(r"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\Python.exe", "")
讀取操作完成了,有些情況下,爲了在測試中,修改一些環境或程序配置,我們需要對註冊表進行寫入操作,看下代碼吧
def req_add(path, key, value, type=_winreg.REG_SZ):
try:
path = path.replace("/", "\\")
rootName = path[:path.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
用法也比較簡單,比如,我們要在Python的路徑下,增加一個選項值,如下:
reg_add(r"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\Python.exe", "test", "test")
轉載請註明:http://blog.csdn.net/sogouauto
探索測試奧義,交流測試技術,歡迎關注“搜狗測試”