def check_tinc_service(self): rRoot = winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE) subDir = r'Software\tinc' curpath = os.getcwd() tincbinpath = os.getcwd() + r"\vnet" tincinscmd = ['sc stop tinc.vnetbridge', 'sc delete tinc.vnetbridge', tincbinpath + r'\tincd.exe -n ' + 'vnetbridge', 'sc stop tinc.vnetbridge', 'sc config tinc.vnetbridge start= demand'] keyHandle = None try: keyHandle = winreg.OpenKey(rRoot, subDir) except Exception as ex: self._log(subDir + " 不存在") self._log(ex) if not keyHandle: keyHandle = winreg.CreateKey(rRoot, subDir) if keyHandle: count = winreg.QueryInfoKey(keyHandle)[1] # 获取该目录下所有键的个数(0-下属键个数;1-当前键值个数) if not count: self._log.info("创建 tinc path:: {0}".format(tincbinpath)) winreg.SetValue(rRoot, subDir, winreg.REG_SZ, tincbinpath) for cmd in tincinscmd: os.popen(cmd) time.sleep(0.1) else: name, key_value, value_type = winreg.EnumValue(keyHandle, 0) if tincbinpath not in key_value: self._log.info("修改 tinc path:: {0}".format(tincbinpath)) winreg.SetValue(rRoot, subDir, winreg.REG_SZ, tincbinpath) for cmd in tincinscmd: os.popen(cmd) time.sleep(0.1)
def execute(self, context): winreg.SetValue(winreg.HKEY_CURRENT_USER, r"Software\Classes\blend1_auto_file\shell\open\command", winreg.REG_SZ, '"'+sys.argv[0]+'" "%1"') for i in range(self.max): i += 1 winreg.SetValue(winreg.HKEY_CURRENT_USER, r"Software\Classes\.blend"+str(i), winreg.REG_SZ, 'blend1_auto_file') self.report(type={"INFO"}, message="The executable file associated with a backup file") return {'FINISHED'}
def registerTypes(types): for t in types: if t.get('command') is None: # No Defined command, therefore set to default result = os.system(f"FTYPE {t.get('type')}=\"%1\" %*") continue result = os.system(f"FTYPE {t.get('type')}={t.get('command')}") if result == 5: # Error code 5: Access deined # Commonly raised when not admin return False try: reg = winreg.ConnectRegistry(None, winreg.HKEY_CLASSES_ROOT) except WindowsError as ex: central.uux.show_warning("Unable to connect to registry, file icons and descriptive names will not be changed.") return for t in types: ty = winreg.OpenKey(winreg.HKEY_CLASSES_ROOT, t.get('type'),access=winreg.KEY_SET_VALUE) winreg.SetValueEx(ty, "FriendlyTypeName",0,winreg.REG_SZ,t.get('name')) image = t.get('image') if image is not None: winreg.SetValue(winreg.HKEY_CLASSES_ROOT, t.get('type'), winreg.REG_SZ, t.get('name')) winreg.SetValue(ty,"DefaultIcon", winreg.REG_SZ, image) winreg.CloseKey(ty) central.uux.show_debug(f"HKEY_CLASSES_ROOT/{t.get('type')}/DefaultIcon =>{image}") return True
def install_win(): try: import winreg except ImportError: import _winreg as winreg SZ = winreg.REG_SZ with winreg.CreateKey(winreg.HKEY_CURRENT_USER, "Software\Classes\.ipynb") as k: winreg.SetValue(k, "", SZ, "Jupyter.nbopen") winreg.SetValueEx(k, "Content Type", 0, SZ, "application/x-ipynb+json") winreg.SetValueEx(k, "PerceivedType", 0, SZ, "document") with winreg.CreateKey(k, "OpenWithProgIds") as openwith: winreg.SetValueEx(openwith, "Jupyter.nbopen", 0, winreg.REG_NONE, b'') executable = sys.executable # if executable.endswith("python.exe"): # executable = executable[:-10] + 'pythonw.exe' launch_cmd = '"{}" -m nbopen "%1"'.format(executable) with winreg.CreateKey(winreg.HKEY_CURRENT_USER, "Software\Classes\Jupyter.nbopen") as k: winreg.SetValue(k, "", SZ, "IPython notebook") with winreg.CreateKey(k, "shell\open\command") as launchk: winreg.SetValue(launchk, "", SZ, launch_cmd) try: from win32com.shell import shell, shellcon shell.SHChangeNotify(shellcon.SHCNE_ASSOCCHANGED, shellcon.SHCNF_IDLIST, None, None) except ImportError: print("You may need to restart for association with .ipynb files to work") print(" (pywin32 is needed to notify Windows of the change)")
def setup_write_win(): """ setup is executed if this program is started without any command line args. """ import winreg as winreg myPath = getMyFile() MyHKEY = HKEY_CURRENT_USER ret = winreg.SetValue( MyHKEY, 'SOFTWARE\Classes\Directory\shell\ScicompFolderActions', REG_SZ, 'SciComp Folder Actions ...') mykey = winreg.OpenKey( MyHKEY, 'SOFTWARE\Classes\Directory\shell\ScicompFolderActions', 0, winreg.KEY_ALL_ACCESS) winreg.SetValueEx(mykey, "Icon", None, REG_SZ, '"%s",0' % myPath) mykey.Close() ret = winreg.SetValue( MyHKEY, 'SOFTWARE\Classes\Directory\shell\ScicompFolderActions\command', REG_SZ, '"%s" --folder "%%1"' % myPath) # ret = winreg.SetValue(MyHKEY,'SOFTWARE\FredHutch\ScicompFolderActions',REG_SZ,'ScicompFolderActions settings') # mykey = winreg.OpenKey(MyHKEY,'SOFTWARE\FredHutch\ScicompFolderActions', 0, winreg.KEY_ALL_ACCESS) # winreg.SetValueEx(mykey, "xxx", None, REG_SZ, "ccc") # winreg.SetValueEx(mykey, "yyy", None, REG_SZ, "hhh") # mykey.Close() return True
def register_xrio_ext(): # register .xrio extention for siemens py try: if getattr(sys, 'frozen', False): exe_path = sys.executable ico_path = os.path.join(os.path.dirname(sys.executable), 'doc.ico') else: return exe_path = '"' + exe_path + '" "%1"' ico_path = ico_path + ",0" key_xrio = winreg.CreateKey(winreg.HKEY_CLASSES_ROOT, r".xrio") winreg.SetValue(key_xrio, None, winreg.REG_SZ, r"SiemensPie.XRio") winreg.SetValue(key_xrio, r"Content Type", winreg.REG_SZ, r"text/html") winreg.CloseKey(key_xrio) key_xrio = winreg.CreateKey(winreg.HKEY_CLASSES_ROOT, r"SiemensPie.XRio") key_di = winreg.CreateKey(key_xrio, r"DefaultIcon") winreg.SetValue(key_di, None, winreg.REG_SZ, ico_path) winreg.CloseKey(key_di) key_sh = winreg.CreateKey(key_xrio, r"shell") key_op = winreg.CreateKey(key_sh, r"open") key_cmd = winreg.CreateKey(key_op, r"command") winreg.SetValue(key_cmd, None, winreg.REG_SZ, exe_path) winreg.CloseKey(key_cmd) winreg.CloseKey(key_op) winreg.CloseKey(key_sh) except: print( "Error at register shell extension for .xrio files, work continues.. \n" ) return
def execute(self, context): winreg.SetValue(winreg.HKEY_CURRENT_USER, r"Software\Classes\.blend", winreg.REG_SZ, 'blend_auto_file') winreg.SetValue( winreg.HKEY_CURRENT_USER, r"Software\Classes\blend_auto_file\shell\open\command", winreg.REG_SZ, '"' + sys.argv[0] + '" "%1"') self.report(type={"INFO"}, message="executable file associated with a.blend file") return {'FINISHED'}
def register_extensions(extensions=extensions, allusers=False): r''' Registers the given extensions as "PyMOL.<ext>" ProgIDs in the Windows registry. ''' cmd = get_cmd() ico = get_icon('pymolfile.ico') ckey = CLASSES(allusers) cache = set() for ext in extensions: primary = ext_get_primary(ext) progid = 'PyMOL.' + primary is_text = ext in texttypes or primary in texttypes print('Registering Extension: ' + ext + ' -> ' + progid) deletekey( HKEY(allusers), r"Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\." + ext + r"\UserChoice") with winreg.CreateKey(ckey, '.' + ext) as key: winreg.SetValue(key, '', winreg.REG_SZ, progid) if progid in cache: continue cache.add(progid) with winreg.CreateKey(ckey, progid) as key: winreg.SetValue(key, r"shell\open\command", winreg.REG_SZ, cmd) winreg.SetValue(key, r"shell\open", winreg.REG_SZ, 'Open with PyMOL') if is_text: winreg.SetValue(key, r"shell\open", winreg.REG_SZ, 'Run with PyMOL') winreg.SetValueEx(key, r"PerceivedType", 0, winreg.REG_SZ, 'text') if primary in ['pse']: winreg.SetValue(key, r"shell\play\command", winreg.REG_SZ, cmd + ' -A6') winreg.SetValue(key, r"shell\play", winreg.REG_SZ, 'Present with PyMOL') if primary in ['psw']: editcmd = cmd[:-4] + ' -d "load %1"' winreg.SetValue(key, r"shell\edit\command", winreg.REG_SZ, editcmd) winreg.SetValue(key, r"shell\edit", winreg.REG_SZ, 'Edit with PyMOL') if primary in descriptions: winreg.SetValueEx(key, r"FriendlyTypeName", 0, winreg.REG_SZ, descriptions[primary]) if ico: winreg.SetValue(key, r"DefaultIcon", winreg.REG_SZ, ico)
def registerToFile(templateName): """ templateName must have extension TODO: windows only allows one "new" per extension. Perhaps make some kind of selector ui?? NOTE: I had to do a full restart to make this work. Is there a better way?? See also: http://mc-computing.com/WinExplorer/WinExplorerRegistry_ShellNew.htm NOTE: besides the things listed, there are also Handler = CLSID IconPath = path ItemName = new item name MenuText = whatever Config->DontRename = ??? """ extension = '.' + templateName.rsplit('.', 1)[1] try: extensionkey = winreg.OpenKey(winreg.HKEY_CLASSES_ROOT, extension) except WindowsError as e: print(e) extensionkey = winreg.CreateKey(winreg.HKEY_CLASSES_ROOT, extension) # todo: follow the default value and get a new key # create or open ShellNew try: key = winreg.OpenKey(extensionkey, 'ShellNew') # since it is present: # 1) copy it to ShellNew.N newkey = winreg.CreateKey(extensionkey, _nextShellNewName(extensionkey)) # 2) create a ShellNew.N+1 for the new stuff below newkey = winreg.CreateKey(extensionkey, _nextShellNewName(extensionkey)) # 3) point original ShellNew to multimenu.py except WindowsError as e2: if str(e2).find( '[Error 2]') >= 0: # did not find the key, so create it try: newkey = winreg.CreateKey(key, 'ShellNew') except WindowsError as e2: if str(e2).find('[Error 5]') >= 0: print(e2) raise Exception('Did you forget to run as administrator?') raise e2 else: raise e cmd = PYTHON_COMMAND cmd = cmd + '"' + HERE + 'newfiles.py" "' + templateName + '" "%v"' winreg.SetValue(key, 'Command', winreg.REG_SZ, cmd) winreg.SetValue(key, 'NullFile', winreg.REG_SZ, cmd) # not sure how necessary this is winreg.FlushKey(key)
def create_command(name, desc, command, filetype, icon): key = winreg.CreateKey(winreg.HKEY_CLASSES_ROOT, "SystemFileAssociations\\" + filetype + "\\shell") comKey = winreg.CreateKey(key, name) winreg.SetValue(key, name, winreg.REG_SZ, desc) if icon is not None: winreg.SetValue(comKey, "Icon", winreg.REG_SZ, icon) winreg.CreateKey(comKey, "command") winreg.SetValue(comKey, "command", winreg.REG_SZ, command) key.Close() comKey.Close()
def execute(self, context): winreg.SetValue(winreg.HKEY_CURRENT_USER, r"Software\Classes\.blend", winreg.REG_SZ, 'blend_auto_file') winreg.SetValue( winreg.HKEY_CURRENT_USER, r"Software\Classes\blend_auto_file\shell\open\command", winreg.REG_SZ, '"' + sys.argv[0] + '" "%1"') self.report( type={"INFO"}, message="Target files have been associated to the current version") return {'FINISHED'}
def addreg(path): try: key = winreg.OpenKey(winreg.HKEY_CLASSES_ROOT, "*\\shell\\") winreg.SetValue(key, "PartExtract-py", winreg.REG_SZ, "NX装配树提取打包") newKey = winreg.OpenKey(winreg.HKEY_CLASSES_ROOT, "*\\shell\\PartExtract-py") value = path + " -p \"%1\"" winreg.SetValue(newKey, "command", winreg.REG_SZ, value) except: wx.MessageBox(u'右键菜单添加失败', u'提示', wx.OK | wx.ICON_ERROR) else: wx.MessageBox(u'成功添加右键菜单', u'提示', wx.OK | wx.ICON_INFORMATION)
def __create_credentials(self): print('Please provide your credentials to connect to {0}'.format( self.db_name)) db_user = input('Please type your username:\n') db_pass = input('Please type your password:\n') HKEY_CURRENT_USER = winreg.HKEY_CURRENT_USER FRO = winreg.OpenKey(HKEY_CURRENT_USER, self.__HKEY_PATH()) # to be implemented: # ask user whether credentials, i.e. password, can be stored in user's registry winreg.SetValue(FRO, self.db_name + 'User', winreg.REG_SZ, db_user) winreg.SetValue(FRO, self.db_name + 'Pass', winreg.REG_SZ, db_pass) self.__user_credentials()
def _addKey(path, Type): key = winreg.OpenKey(winreg.HKEY_CLASSES_ROOT, Type) name = os.path.basename(path) i = name.index(".") if i != -1: name = name[:name.index(".")] name = f"open with {name}" winreg.SetValue(key, name, winreg.REG_SZ, name) nameKey = winreg.OpenKey(key, name) winreg.SetValue(nameKey, 'command', winreg.REG_SZ, f"{path} %1") winreg.CloseKey(nameKey) winreg.CloseKey(key)
def install_association(): """Installs a file association for the LilyPond file type. Sets HKEY_CLASSES_ROOT\\LilyPond\\shell\\frescobaldi to 'Open with &Frescobaldi...' Sets HKEY_CLASSES_ROOT\\LilyPond\\shell\\frescobaldi\\command to '{python} "{script}" "%1"' """ key = winreg.CreateKey(winreg.HKEY_CLASSES_ROOT, "LilyPond\\shell\\frescobaldi") with key: winreg.SetValue(key, None, winreg.REG_SZ, "Open with &Frescobaldi...") winreg.SetValue(key, "command", winreg.REG_SZ, '{0} "{1}" "%1"'.format(python, script)) print("* Created file association")
def DllRegisterServer(prog_files_dir): executable_path = os.path.sep.join([os.path.dirname(sys.executable), "pythonw.exe"]) folder_key = winreg.CreateKey(winreg.HKEY_CLASSES_ROOT, "Directory\\Background\\shell\\tracker_player") winreg.SetValue(winreg.HKEY_CLASSES_ROOT, "Directory\\Background\\shell\\tracker_player", winreg.REG_SZ, "Tracker Player") folder_subkey = winreg.CreateKey(folder_key, "command") winreg.SetValue(folder_key, "command", winreg.REG_SZ, r'"{}" "{}\TrackerPlayer.pyw"'.format(executable_path, prog_files_dir))
def reg_visual_studio(dstpath): rkey = reg.CreateKey(reg.HKEY_LOCAL_MACHINE, 'SOFTWARE\Microsoft\VisualStudio\SxS') reg.SetValue(reg.CreateKey(rkey, 'VS7'), '14.0', reg.REG_SZ, dstpath) vc_key = reg.CreateKey(rkey, 'VC7') reg.SetValue(vc_key, '14.0', reg.REG_SZ, os.path.join(dstpath)) # NETFRAMEWORK register # folder and version osbit = get_app_bit(dstpath) ver = os.path.basename(dstpath) fwk_folder = input("Enter .NET Framework Directory:") reg.SetValue(vc_key, 'FrameWorkDir{0}'.format(osbit), reg.REG_SZ, fwk_folder) fwk_ver = input("Enter .NET Framework Version:") reg.SetValue(vc_key, 'FrameWorkVer{0}'.format(osbit), reg.REG_SZ, fwk_ver)
def addFile(): Path = os.path.realpath(sys.argv[0]) key = winreg.OpenKey(winreg.HKEY_CLASSES_ROOT, r'SystemFileAssociations') NewKey = winreg.CreateKey(key, ".py") winreg.CloseKey(key) key = winreg.CreateKey(NewKey, 'shell') winreg.CloseKey(NewKey) NewKey = winreg.CreateKey(key, 'Pypacker') winreg.CloseKey(key) winreg.SetValue(NewKey, '', winreg.REG_SZ, "用 Pypacker 打开") newkey = winreg.CreateKey(NewKey, "command") winreg.CloseKey(NewKey) winreg.SetValue(newkey, '', winreg.REG_SZ, '\"{}\" \"%1\"'.format(Path)) winreg.CloseKey(newkey)
def registerBatFile(ext, bat, name): import winreg as wr ext_key = wr.CreateKey(wr.HKEY_CLASSES_ROOT, '.' + ext) try: auto_file = wr.EnumValue(ext_key, 0)[1] except: auto_file = ext + '_auto_file' wr.SetValue(ext_key, '', wr.REG_SZ, auto_file) key = wr.CreateKey(wr.HKEY_CLASSES_ROOT, auto_file) key = wr.CreateKey(key, 'shell') key = wr.CreateKey(key, name) key = wr.CreateKey(key, 'command') wr.SetValue(key, '', wr.REG_SZ, '"' + bat + '" "%1"')
def getOrSetlastOpenDir(self, path: str = None): """返回或设置最后打开文件夹,如果path给一个文件名或路径名,则设置,不给值则返回一个值""" subKey = r'Software\project_m' key = winreg.HKEY_CURRENT_USER try: newkey = winreg.OpenKey(key, subKey) except WindowsError: newkey = winreg.CreateKey(key, subKey) winreg.SetValue(newkey, "recentPath", winreg.REG_SZ, getcwd()) if not path: return winreg.QueryValue(key, subKey + r'\recentPath') else: if ospath.isfile(path): path = ospath.dirname(path) winreg.SetValue(newkey, "recentPath", winreg.REG_SZ, path)
def run(self): pool_type = str(self.pool_type_list.currentText()) coin_type = str(self.coin_type_list.currentText()) conf_path = self.conf_path.text() key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, r"SOFTWARE") new_key = winreg.CreateKey(key, "Minerhelper") winreg.SetValue(new_key, "pool_type", winreg.REG_SZ, pool_type) winreg.SetValue(new_key, "coin_type", winreg.REG_SZ, coin_type) winreg.SetValue(new_key, "conf_path", winreg.REG_SZ, conf_path) os.chdir(os.path.dirname(conf_path)) try: worker_id = make_id_from_file(conf_path, pool_type, coin_type) print(worker_id) print('in run') except: msg = QMessageBox() msg.setWindowTitle("提示") msg.setText("配置信息不正确,请检查文件位置和内容!") msg.exec_() return # check the user has signed up # try: # if not login(worker_id): # msg = QMessageBox() # msg.setIcon(QMessageBox.Information) # # msg.setText("认证失败,请注册之后再使用!") # msg.setWindowTitle("提示") # msg.setStandardButtons(QMessageBox.Ok) # # msg.exec_() # return # except: # return self.heart_beat_thread = HeartBeatThread(worker_id, conf_path, coin_type) self.heart_beat_thread.daemon = True self.heart_beat_thread.start() self.pool_type_list.setEnabled(False) self.coin_type_list.setEnabled(False) self.conf_btn.setEnabled(False) self.run_btn.setEnabled(False) self.auto_run_check.setEnabled(False) self.stop_btn.setEnabled(True)
def config_win(): try: key = winreg.CreateKey(winreg.HKEY_LOCAL_MACHINE,r'SOFTWARE\Classes\intratech-stag' ) winreg.SetValue(key, '', winreg.REG_SZ, 'Url:Smartag Protocol') winreg.SetValueEx(key, 'URL Protocol', 0 , winreg.REG_SZ, '') winreg.CloseKey(key) key = winreg.CreateKey(winreg.HKEY_LOCAL_MACHINE,r'SOFTWARE\Classes\intratech-stag\shell\open\command' ) # winreg.SetValue(key,'',winreg.REG_SZ, '"{0}" "%1"'.format(os.normpath(os.path.abspath(sys.executable)))) winreg.SetValue(key,'',winreg.REG_SZ, r'smarttag_protocolhandler.exce "%1"') winreg.CloseKey(key) except(OSError, ImportError): print(Col.FAIL + ' FAILED to setup registry link for SmartTag scheme!' + Col.OFF) sleep(wait_time) sys.exit(2)
def install_program(): # Running always ''' This function running every time and checking if the program added to right-ckick-menu. If not, trying to edit the regedit for adding itself ''' path_to_program = sys.argv[0] # sys.executable returns str(path to interpreter) like path + 'pythonw.exe', # (w in the end - without stdin/ stdout), but needs just 'python.exe' path_to_python = (sys.executable.replace('pythonw.exe', 'python.exe') if ('pythonw.exe' in sys.executable) else sys.executable) reg_value = '\"{0}\" \"{1}\" \"{2}\"'.format(path_to_python, path_to_program, "%1") # Only double quotes! try: # Try to read reg value winreg.QueryValue(key, subkey) print(dialog['info'][0]) # The program already installed except: try: # Create reg branch+value to get file path via context menu winreg.CreateKey(key, subkey) winreg.SetValue(key, subkey, winreg.REG_SZ, reg_value) print(dialog['info'][1]) print(dialog['info'][2]) except Exception as error: print(dialog['common'][1]) # Something went wrong :( input(f'Error: {error}') sys.exit()
def file_associations_cleanup(): extensions = ['.msh', '.geo', '.stl'] # Linux file associations are done together with desktop items # MacOS file associations are set using the .app files if sys.platform in ['linux', 'darwin']: return if sys.platform == 'win32': with winreg.OpenKey(winreg.HKEY_CURRENT_USER, r'Software\Classes', access=winreg.KEY_WRITE) as reg: # Remove SimNIBS Gmsh call from the registry try: winreg.QueryValue( reg, rf'SimNIBS.Gmsh.v{MINOR_VERSION}\shell\open\command') except FileNotFoundError: pass else: # Delete recursivelly paths = rf'SimNIBS.Gmsh.v{MINOR_VERSION}\shell\open\command'.split( '\\') for i in reversed(range(len(paths))): try: winreg.DeleteKey(reg, '\\'.join(paths[:i + 1])) except OSError: break # Remove the extensions from the registry for ext in extensions: try: entry = winreg.QueryValue(reg, ext) except FileNotFoundError: pass else: if entry == fr'SimNIBS.Gmsh.v{MINOR_VERSION}': winreg.SetValue(reg, ext, winreg.REG_SZ, '')
def _doregister(mod_name, dll_name): assert os.path.isfile( dll_name), "Shouldn't get here if the file doesn't exist!" try: key = winreg.OpenKey( winreg.HKEY_LOCAL_MACHINE, "Software\\Python\\PythonCore\\%s\\Modules\\%s" % (sys.winver, mod_name), ) except winreg.error: try: key = winreg.OpenKey( winreg.HKEY_LOCAL_MACHINE, "Software\\Python\\PythonCore\\%s\\Modules\\%s" % (sys.winver, mod_name), ) except winreg.error: print( "Could not find the existing '%s' module registered in the registry" % (mod_name, )) usage_and_die(4) # Create the debug key. sub_key = winreg.CreateKey(key, "Debug") winreg.SetValue(sub_key, None, winreg.REG_SZ, dll_name) print("Registered '%s' in the registry" % (dll_name, ))
def run(self): if not platform.system() == "Windows": print("Registering as context menu entry is only supported " "on Windows systems!") return appdata_dir = self._create_appdata_dir() bat = self._copy_to_dir("context_menu_entry/white_brush.bat", appdata_dir) icon = self._copy_to_dir("context_menu_entry/white_brush.ico", appdata_dir) import winreg as wr aReg = wr.ConnectRegistry(None, wr.HKEY_CURRENT_USER) # replace path to python and path to script below! aKey = wr.OpenKey(aReg, r"Software\Classes\*\shell", 0, wr.KEY_WRITE) try: newKey = wr.CreateKey(aKey, "Whitebrush") wr.SetValue(newKey, "command", wr.REG_SZ, f'"{bat}" "%1"') wr.SetValueEx(newKey, "Icon", 0, wr.REG_SZ, f'"{icon}"') except EnvironmentError: print("Encountered problems writing into the Registry...") wr.CloseKey(aKey) print("Successfully updated registry") wr.CloseKey(aReg)
def create_root_key(): try: new_key = winreg.OpenKeyEx(winreg.HKEY_CLASSES_ROOT, r"Directory\\Background\\shell", 0, winreg.KEY_ALL_ACCESS) key = winreg.CreateKey(new_key, r"powfu") winreg.SetValue(key, "", winreg.REG_SZ, "Organize with PowFu - File Organizer") sub_key = winreg.CreateKey(key, r"command") winreg.SetValue(sub_key, "", winreg.REG_SZ, os.path.join(full, "powfu.exe")) winreg.CloseKey(new_key) winreg.CloseKey(key) winreg.CloseKey(sub_key) except WindowsError as we: raise "Ops! Something went wrong"
def setup_file_association(force=False, silent=False): # Linux and OSX file associations are done together with desktop items if sys.platform != 'win32': return gmsh_bin = file_finder.path2bin('gmsh') extensions = ['.msh', '.geo', '.stl'] associate = dict.fromkeys(extensions) for ext in extensions: if _is_associated(ext): if force: associate[ext] = True else: associate[ext] = _get_input( f'Found other association for "{ext}" files, overwrite it?', silent) else: associate[ext] = True # If all rejected, return if not any(associate.values()): return if sys.platform == 'win32': with winreg.OpenKey(winreg.HKEY_CURRENT_USER, r'Software\Classes', access=winreg.KEY_WRITE) as reg: winreg.CreateKey( reg, rf'SimNIBS.Gmsh.v{MINOR_VERSION}\shell\open\command') winreg.SetValue( reg, rf'SimNIBS.Gmsh.v{MINOR_VERSION}\shell\open\command', winreg.REG_SZ, f'"{gmsh_bin}" "%1"') for ext in extensions: try: value = winreg.QueryValue(reg, ext) except FileNotFoundError: register = True else: if value: register = _get_input( f'Found other association for "{ext}" files, overwrite it?', silent) else: register = True if register: winreg.CreateKey(reg, ext) winreg.SetValue(reg, ext, winreg.REG_SZ, fr'SimNIBS.Gmsh.v{MINOR_VERSION}')
def time_handle(self): if self.timer.get() <= 0: self.master.destroy() else: self.after(1000, self.time_handle) self.timer.set(self.timer.get() - 1) winreg.SetValue(self.reg, "Timer", winreg.REG_SZ, str(self.timer.get()))
def config_win(): try: import winreg as reg key = reg.CreateKey(reg.HKEY_CURRENT_USER, 'SOFTWARE\\Classes\\nzblnk') reg.SetValue(key, '', reg.REG_SZ, 'URL:nzblnk') reg.SetValueEx(key, 'URL Protocol', 0, reg.REG_SZ, '') reg.CloseKey(key) key = reg.CreateKey(reg.HKEY_CURRENT_USER, 'SOFTWARE\\Classes\\nzblnk\\shell\\open\\command') reg.SetValue(key, '', reg.REG_SZ, '"{0}" "%1"'.format(op.normpath(os.path.abspath(sys.executable)))) reg.CloseKey(key) except (OSError, ImportError): print(Col.FAIL + ' FAILED to setup registry link for NZBLNK scheme!' + Col.OFF) sleep(wait_time) sys.exit(2)