2017-03-05 63 views
1

我想在Windows 7的Run键下创建一个新的值。我正在使用Python 3.5,并且在写入密钥时遇到了问题。我目前的代码是在我试图修改其值的密钥下创建一个新密钥。在注册表中创建新值使用Python运行键?

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

当我运行它,它使运行并将其命名为“NameOfNewKey”下一个键,然后设置默认值到的calc.exe路径。但是,我想向Run键添加一个新值,以便在启动时运行calc.exe。

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

+0

你试过手动首先添加它,确保它的工作原理?然后尝试将其转换为代码? –

+0

上面这个不是按预期工作的。即使我在Run键下添加一个值,它也只是在Run键下创建一个新键,而不是在Run键下创建一个值。编辑 - 找到答案,放入OP。 – sqlsqlsql

+0

你可以把你的完整的代码片段,以确保任何人在未来来到这里有一个工作代码示例看?谢谢 –

回答

0

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

代码:

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