简体   繁体   中英

Python: can't add a file to the startup in registry

i browsed a lot to undestand how to do this and all the sites i visited show quite the same solution:

import winreg as reg

key="HKEY_CURRENT_USER"
key_value=r"Software\Microsoft\Windows\CurrentVersion\Run"

opening=reg.OpenKey(reg.HKEY_CURRENT_USER, key_value, 0, reg.KEY_ALL_ACCESS)

reg.SetValueEx(opening, "test", 0, reg.REG_SZ, r"\C:\Users\vitto\OneDrive\Desktop\python\p32.py")

reg.CloseKey(opening)

the code doesn't return any error but if i check the registry there's nothing there, even if i run the script as administrator. I know i could use simply the folder "C:\Users\user\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup" but i need to do this for my project.

this function worked for me:

def reg_presist(REG_PATH, key, value):
  reg_key = winreg.OpenKey(winreg.HKEY_CURRENT_USER,REG_PATH,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)

reg_presist(r'Software\Microsoft\Windows\CurrentVersion\Run','Script', script_path)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM