Creating new value inside registry Run key with Python?

眉间皱痕 提交于 2019-12-22 18:32:28

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/42605055/creating-new-value-inside-registry-run-key-with-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!