在注册表中创建新值使用Python运行键?

时间:2017-03-05 06:00:43

标签: python python-3.x pywin32

我正在尝试在Windows 7中的Run键下创建一个新值。我正在使用Python 3.5而我在写入密钥时遇到问题。我当前的代码是在我试图修改。的值的密钥下创建一个新密钥。

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')

当我运行它时,它在Run下创建一个键并将其命名为“NameOfNewKey”,然后将默认值设置为calc.exe路径。但是,我想在Run键中添加一个新值,这样当我启动时,calc.exe将会运行。

编辑:我找到了答案。它应该是SetValueEx函数而不是SetValue。

1 个答案:

答案 0 :(得分:1)

这是一个可以设置/删除运行键的功能。

<强>代码:

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)

设置:

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

删除:

set_run_key('NameOfNewValue', None)

导入win32个库:

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