Search code examples
pythonpython-3.xpywin32

Creating new value inside registry Run key with Python?


I am trying to create a new value under the Run key in Windows 7. I am using Python 3.5 and I am having trouble writing to the key. My current code is creating a new key under the key I am trying to modify the values of.

from winreg import *

aKey = OpenKey(HKEY_CURRENT_USER, "Software\Microsoft\Windows\CurrentVersion\Run", 0, KEY_ALL_ACCESS)

SetValue(aKey, 'NameOfNewValue', REG_SZ, '%windir%\system32\calc.exe')

When I run this, it makes a key under the Run and names it "NameOfNewKey" and then sets the default value to the calc.exe path. However, I want to add a new value to the Run key so that when I startup, calc.exe will run.

EDIT: I found the answer. It should be the SetValueEx function instead of SetValue.


Solution

  • Here is a function which can set/delete a run key.

    Code:

    def set_run_key(key, value):
        """
        Set/Remove Run Key in windows registry.
    
        :param key: Run Key Name
        :param value: Program to Run
        :return: None
        """
        # This is for the system run variable
        reg_key = winreg.OpenKey(
            winreg.HKEY_CURRENT_USER,
            r'Software\Microsoft\Windows\CurrentVersion\Run',
            0, winreg.KEY_SET_VALUE)
    
        with reg_key:
            if value is None:
                winreg.DeleteValue(reg_key, key)
            else:
                if '%' in value:
                    var_type = winreg.REG_EXPAND_SZ
                else:
                    var_type = winreg.REG_SZ
                winreg.SetValueEx(reg_key, key, 0, var_type, value)
    

    To set:

    set_run_key('NameOfNewValue', '%windir%\system32\calc.exe')
    

    To remove:

    set_run_key('NameOfNewValue', None)
    

    To import win32 libs:

    try:
        import _winreg as winreg
    except ImportError:
        # this has been renamed in python 3
        import winreg