Python模塊_winreg操作注冊表


用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)

  給新建的key賦值: _winreg.SetValue(key,sub_key,type,value)

例子:

#!/usr/bin/env python

#coding=utf-8

import _winreg

 

key=_winreg.OpenKey(_winreg.HKEY_CURRENT_USER,r"Software\Microsoft\Windows\CurrentVersion\Explorer")

#刪除鍵

_winreg.DeleteKey(key, "Advanced")

#刪除鍵值

_winreg.DeleteValue(key, "IconUnderline")

#創建新的

newKey = _winreg.CreateKey(key,"MyNewkey")

    #給新創建的鍵添加鍵值

_winreg.SetValue(newKey,"ValueName",0,"ValueContent")


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM