vks
vks

Reputation: 67968

Registry change through python working incorrectly

import _winreg as registry
key=registry.OpenKey(registry.HKEY_CURRENT_USER,"Software\Microsoft\Windows\CurrentVersion\Internet Settings",0,registry.KEY_ALL_ACCESS)
proxy=proxy_server+":"+proxy_port
registry.SetValue(key, 'ProxyEnable', registry.REG_SZ, 'dword:00000001')
registry.SetValue(key, 'ProxyServer', registry.REG_SZ, proxy)

I am using the above code to set proxy.But it does not add a new key in internet setting.Instead creates a new folder and put in a key named default with the values provided.

enter image description here

Can anybody help me on this.Really stuck

Upvotes: 2

Views: 1844

Answers (1)

martineau
martineau

Reputation: 123393

Although I don't understand why your code doesn't work, I was able to reproduce the problem as well as come up with a workaround—which is to just do the equivalent thing via the _winreg.SetValueEx() function.

Code with that trivial change is shown below. I also added a r prefix to the key string constant since it contains literal backslash characters (but that wasn't causing the issue). (Note I also changed the names and values of a few literals so as not to conflict with anything that might be in the registry of my own system.)

import _winreg as registry

proxy_server = 'some_proxy_server'  # dummy value
proxy_port = 'some_proxy_port'      # dummy value

key = registry.OpenKey(registry.HKEY_CURRENT_USER,
                       r"Software\Microsoft\Windows\CurrentVersion\Internet Settings",
                       0, registry.KEY_ALL_ACCESS)
proxy = proxy_server + ":" + proxy_port

# SetValue doesn't work for some reason...
#registry.SetValue(key, '_ProxyEnable', registry.REG_SZ, 'dword:00000001')
#registry.SetValue(key, '_ProxyServer', registry.REG_SZ, proxy)

# but SetValueEx does work
registry.SetValueEx(key, "_ProxyEnable", 0, registry.REG_SZ, "dword:00000001")
registry.SetValueEx(key, "_ProxyServer", 0, registry.REG_SZ, proxy)

I also must comment that setting ProxyEnable to a string value of "dword:00000001" instead of a REG_DWORD value of 1 seems a bit odd...but it's what your code was attempting to do.

screenshot showing properly changed value in registry editor

Upvotes: 6

Related Questions