import _winreg:用python操作修改windows注册表
?
用python操作修改windows注冊表,顯然要比用C或者C++簡單。
??? 主要參考資料:官方文檔:http://docs.python.org/library/_winreg.html
通過 python 操作注冊表主要有兩種方式,一種是通過 python 的內置模塊 _winreg ,另一種方式就是 Win32 Extension For Python 的 win32api 模塊。這里主要簡單看看用內置模塊 _winreg 如何操作注冊表。
?
1. 讀取
讀取用的方法是 OpenKey 方法:打開特定的 key
_winreg.OpenKey(key,sub_key,res=0,sam=KEY_READ)
例子 :此例子是顯示了本機網絡配置的一些注冊表項
#!/usr/bin/env python
#coding=utf-8
?
import _winreg
?
key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, ???????????????????? r"SYSTEM/CurrentControlSet/Services/Tcpip/Parameters/Interfaces/{0E184877-D910-4877-B 4C2-04F487B6DBB7}")
# 獲取該鍵的所有鍵值,遍歷枚舉
try:
??? i=0
??? while 1:
??????? #EnumValue 方法用來枚舉鍵值, EnumKey 用來枚舉子鍵
??????? name,value,type = _winreg.EnumValue(key,i)
??????? print repr(name),value,type
??????? i+=1
except WindowsError:
??? print ??????
# 假如知道鍵名,也可以直接取值
value,type = _winreg.QueryValueEx(key,"DhcpDefaultGateway")
print " 默認網關地址 ----",value,type
?
運行的結果如下:
'UseZeroBroadcast' 0 4
'EnableDeadGWDetect' 1 4
'EnableDHCP' 1 4
'IPAddress' [u'0.0.0.0'] 7
'SubnetMask' [u'0.0.0.0'] 7
'DefaultGateway' [] 7
'DefaultGatewayMetric' [] 7
'NameServer' 10.0.0.10 1
'Domain'? 1
'RegistrationEnabled' 1 4
'RegisterAdapterName' 0 4
'TCPAllowedPorts' [u'0'] 7
'UDPAllowedPorts' [u'0'] 7
'RawIPAllowedProtocols' [u'0'] 7
'NTEContextList' [u'0x00000004'] 7
'DhcpClassIdBin' None 3
'DhcpServer' 10.104.4.1 1
'Lease' 907200 4
'LeaseObtainedTime' 1264122113 4
'T1' 1264575713 4
'T2' 1264915913 4
'LeaseTerminatesTime' 1265029313 4
'IPAutoconfigurationAddress' 0.0.0.0 1
'IPAutoconfigurationMask' 255.255.0.0 1
'IPAutoconfigurationSeed' 0 4
'AddressType' 0 4
'IsServerNapAware' 0 4
'DhcpIPAddress' 10.104.5.15 1
'DhcpSubnetMask' 255.255.254.0 1
'DhcpRetryTime' 453598 4
'DhcpRetryStatus' 0 4
'DhcpNameServer' 10.0.0.10 1
'DhcpDefaultGateway' [u'10.104.4.1'] 7
'DhcpSubnetMaskOpt' [u'255.255.254.0'] 7
?
默認網關地址 ---- [u'10.104.4.1'] 7
?
2. 創建 修改注冊表
? 創建 key : _winreg.CreateKey(key,sub_key)
? 刪除 key: _winreg.DeleteKey(key,sub_key)
? 刪除鍵值: _winreg.DeleteValue(key,value)
總結
以上是生活随笔為你收集整理的import _winreg:用python操作修改windows注册表的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: lambda--整理的部分网络博文
- 下一篇: Python 打印不换行