Creating new value inside registry Run key with Python?

Question:

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, "SoftwareMicrosoftWindowsCurrentVersionRun", 0, KEY_ALL_ACCESS)

SetValue(aKey, 'NameOfNewValue', REG_SZ, '%windir%system32calc.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.

Asked By: sqlsqlsql

||

Answers:

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'SoftwareMicrosoftWindowsCurrentVersionRun',
        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%system32calc.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
Answered By: Stephen Rauch

I ran into this same problem. The source of confusion here is the poorly named functions:

  • winreg.SetValue(): sets or creates a subkey
  • winreg.SetValueEx(): sets or creates a named value

Normally when a function has an "Ex" suffix, it means the caller can specify additional arguments for the same operation. In this case, the functions have different semantics; the "SetValue()" should have been named something like "SetKey()".

Answered By: Roland Fernandez
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.