Creating new value inside registry Run key with Python?
Asked Answered
G

2

8

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.

Grison answered 5/3, 2017 at 6:0 Comment(3)
Have you tried manually adding it first, making sure it works? Then trying to convert that into code?Digestion
This above is not working as intended. Even if I add a value under the Run key it will just make a new key under the Run key instead of making a value under the Run key. Edit - Found the answer, put in OP.Grison
can you put your full code snippet in just to make sure anyone who comes here in future has a working code sample to look at? ThanksDigestion
T
5

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
Thulium answered 5/3, 2017 at 6:18 Comment(1)
Works perfectly for me.Chukchi
S
2

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()".

Superscription answered 25/11, 2022 at 22:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.