Jay Pagnis
Jay Pagnis

Reputation: 1110

python 2.6 create volatile registry entry

I am trying to create a volatile registry entry.

Initially I had tried to create something like this but it failed

First Approach

aReg = ConnectRegistry(None, HKEY_CURRENT_USER)
key = CreateKey(HKEY_CURRENT_USER, volatilePath)
Registrykey= OpenKey(HKEY_CURRENT_USER, volatilePath, 0, KEY_WRITE)
SetValueEx(Registrykey,"pid", 0, REG_SZ, "1234")
CloseKey(Registrykey)

Second approach

aReg = ConnectRegistry(None, HKEY_CURRENT_USER)
key = CreateKey(HKEY_CURRENT_USER, volatilePath)
Registrykey= OpenKey(HKEY_CURRENT_USER, volatilePath, 0, KEY_WRITE)
SetValueEx(Registrykey, "pid", 0, REG_SZ|REG_OPTION_VOLATILE, "1234")
CloseKey(Registrykey)

Finally seeing that the key is not working as volatile (working as a normal key), I want to call the Windows native function that is specified here. I am new to Python. Any help will be highly appreciated.

An Update: Latest approach (Still not working)

from ctypes import windll
from _winreg import *  
import win32api
p=PySECURITY_ATTRIBUTES(None, None)
advapi32 = windll.LoadLibrary ( 'advapi32.dll' )
win32api.RegCreateKeyEx(HKEY_CURRENT_USER, u"Volatile Environment", 0, None, REG_OPTION_VOLATILE, KEY_ALL_ACCESS | KEY_WOW64_32KEY, p )
Registrykey= OpenKey(HKEY_CURRENT_USER, volatilePath, 0, KEY_WRITE)
SetValueEx(Registrykey, "pid", 0, REG_SZ, "1234")

Here I am getting an error,

TypeError: 'NoneType' object is not callable

Upvotes: 0

Views: 407

Answers (1)

Eryk Sun
Eryk Sun

Reputation: 34270

If you need a standard-library solution, use ctypes. However, if adding an external dependency to your project is acceptable, I recommend to instead use PyWin32's win32api.RegCreateKeyEx, especially if you're not experienced in C. For pip installation, PyWin32 is available on PyPI as pypiwin32, but it's not availble there for Python 2.6. If possible you should upgrade to the latest version of Python 2.7.

PyWin32 example:

import winnt
import win32api
import win32con

hKey, flag = win32api.RegCreateKeyEx(
                    win32con.HKEY_CURRENT_USER, 
                    'Volatile Environment', 
                    win32con.KEY_ALL_ACCESS, 
                    Options=winnt.REG_OPTION_VOLATILE)

win32api.RegSetValueEx(hKey, 'pid', 0, winnt.REG_SZ, '1234')

FYI, you don't need KEY_WOW64_32KEY access for the HKEY_CURRENT_USER hive. WOW64 redirection only affects keys in HKEY_LOCAL_MACHINE.

Upvotes: 2

Related Questions