def getSystemIcon(forFile): """ get the sysem icon for a file type """ if not isinstance(forFile, str): forFile = forFile.path ext = '.' + forFile.rsplit('.', 1)[-1] icon = None try: key = winreg.OpenKey(winreg.HKEY_CLASSES_ROOT, ext, 0, winreg.KEY_READ) try: icon = winreg.QueryValue(key, 'DefaultIcon') except WindowsError: pass nextKey = winreg.QueryValue(key, None) #print ext,'->',nextKey key = winreg.OpenKey(winreg.HKEY_CLASSES_ROOT, nextKey, 0, winreg.KEY_READ) try: icon = winreg.QueryValue(key, 'DefaultIcon') except WindowsError: pass except WindowsError as e: print(e) return icon
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 find_browsers(): try: import winreg as _winreg except: import _winreg windir = os.getenv('windir') key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, os.path.join('Software', 'Clients', 'StartMenuInternet')) count = _winreg.QueryInfoKey(key)[0] browsers = [] while count > 0: subkey = _winreg.EnumKey(key, count - 1) try: browsers.append({ 'name': _winreg.QueryValue(key, subkey), 'command': _winreg.QueryValue(key, os.path.join(subkey, 'shell', 'open', 'command')) }) except: pass count -= 1 if os.path.exists(os.path.join(windir, 'SystemApps', 'Microsoft.MicrosoftEdge_8wekyb3d8bbwe', 'MicrosoftEdge.exe')): browsers.append({ 'name': 'Microsoft Edge', 'command': os.path.join(windir, 'explorer.exe') + ' "microsoft-edge:%s "' }) return browsers
def init(): key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, r"SOFTWARE\Minerhelper") conf_path = winreg.QueryValue(key, "conf_path") # print(conf_path) pool_type = winreg.QueryValue(key, "pool_type") coin_type = winreg.QueryValue(key, "coin_type") return [conf_path, pool_type, coin_type]
def getWindowsPDFViewer(): try: import winreg # HKCR/.pdf: gives the class of the PDF program. # Example : AcroRead.Document or FoxitReader.Document key = winreg.OpenKey(winreg.HKEY_CLASSES_ROOT, ".pdf") pdfClass = winreg.QueryValue(key, "") # HKCR/<class>/shell/open/command: the path to the PDF viewer program # Example: "C:\Program Files\Acrobat 8.0\acroread.exe" "%1" key2 = winreg.OpenKey(winreg.HKEY_CLASSES_ROOT, pdfClass + r"\shell\open\command") # Almost every PDF program out there accepts passing the PDF path # as the argument, so we don't parse the arguments from the # registry, just get the program path. path = winreg.QueryValue(key2, "").split('"')[1] if fileExists(path): return path except: pass return None
def find_command(cmd): """ Convert a command into a script name, if possible, and find any associated executable. :param cmd: The command (e.g. 'hello') :returns: A 2-tuple. The first element is an executable associated with the extension of the command script. The second element is the script name, including the extension and pathname if found on the path. Example for 'hello' might be (r'c:/Python/python.exe', r'c:/MyTools/hello.py'). """ result = None cmd = which(cmd) if cmd: if cmd.startswith('.\\'): # pragma: no cover cmd = cmd[2:] _, extn = os.path.splitext(cmd) HKCR = winreg.HKEY_CLASSES_ROOT try: ftype = winreg.QueryValue(HKCR, extn) path = os.path.join(ftype, 'shell', 'open', 'command') s = winreg.QueryValue(HKCR, path) exe = None m = COMMAND_RE.match(s) if m: # pragma: no cover exe = m.groups()[0] result = exe, cmd except OSError: # pragma: no cover pass return result
def find_makensis_win(): """Locate makensis.exe on Windows by querying the registry""" try: nsis_install_dir = winreg.QueryValue(winreg.HKEY_LOCAL_MACHINE, 'SOFTWARE\\NSIS') except OSError: nsis_install_dir = winreg.QueryValue(winreg.HKEY_LOCAL_MACHINE, 'SOFTWARE\\Wow6432Node\\NSIS') return pjoin(nsis_install_dir, 'makensis.exe')
def main(): with reg.OpenKey(reg.HKEY_LOCAL_MACHINE, sub_key) as base: backup = [] names = set() deletes = [] renames = [] i = 0 while True: try: name = reg.EnumKey(base, i) value = reg.QueryValue(base, name) except OSError: break backup.append((name, value)) core = name.strip() if core in names: deletes.append(name) else: names.add(core) if core in boost: core = ' ' + core if core != name: renames.append((name, core)) i += 1 if deletes or renames: print('Write backup file', backup_filename) with codecs.open(backup_filename, 'w', 'utf_16_le') as backup_file: wr = backup_file.write wr('\ufeff') wr('Windows Registry Editor Version 5.00\r\n\r\n') wr('[{}]\r\n\r\n'.format(key)) for name, value in backup: wr('[{}\\{}]\r\n'.format(key, name)) wr('@="{}"\r\n\r\n'.format(value)) for name in deletes: print('Delete', repr(name)) reg.DeleteKey(base, name) for old_name, new_name in renames: print('Rename', repr(old_name), 'to', repr(new_name)) value = reg.QueryValue(base, old_name) reg.CreateKey(base, new_name) reg.SetValue(base, new_name, reg.REG_SZ, value) reg.DeleteKey(base, old_name) # print('Restart Windows Explorer') # if not os.system('taskkill /F /IM explorer.exe'): # os.system('start explorer.exe') else: print('Nothing to rename')
def _find_blender_in_windows_registry(): """Tries to locate Blender using the Windows registry @returns The path to the Blender executable or None if not found""" commands = [] # There is no clear install path in the registry (and the one there is has a GUID-like # number in front of it, so it's likely not future-proof). So we'll check the file # association for .blend files. If this fails, we can still scour the system's # "Program Files" directory. try: blendfile_key = winreg.OpenKey( winreg.HKEY_LOCAL_MACHINE, 'SOFTWARE\\Classes\\blendfile\\shell\\open\\command', 0, winreg.KEY_READ) commands.append(winreg.QueryValue(blendfile_key, str())) winreg.CloseKey(blendfile_key) except FileNotFoundError: pass try: blendfile_key = winreg.OpenKey(winreg.HKEY_CLASSES_ROOT, 'blendfile\\shell\\open\\command', 0, winreg.KEY_READ) commands.append(winreg.QueryValue(blendfile_key, str())) winreg.CloseKey(blendfile_key) except FileNotFoundError: pass candidates = [] # Now we have a few "commands" which invoke a program when .blend files are # opened on the system. Extract the path of the program they're invoking. for command in commands: matches = re.findall(r'\"(.+?)\"', command) if not (matches is None): length = len(matches) if length > 0: candidates.append(matches[0]) # Finally, the program may be something else, so look for a candidate that # points to an actually existing path to a file with the name "blender.exe" in it for candidate in candidates: if os.path.isfile(candidate): if 'blender.exe' in candidate.lower(): return candidate return None
def _find_sumatra_exe(self): if hasattr(SumatraViewer, '_sumatra_exe'): return SumatraViewer._sumatra_exe # Sumatra's installer writes the location of the exe to the # App Paths registry key, which we can access using the winreg # module. try: with winreg.OpenKey( winreg.HKEY_LOCAL_MACHINE, 'SOFTWARE\\Microsoft\\Windows\\CurrentVersion' '\\App Paths\\SumatraPDF.exe') as hndl: SumatraViewer._sumatra_exe = winreg.QueryValue(hndl, '') return SumatraViewer._sumatra_exe except WindowsError: pass paths = [ os.path.expandvars("%PROGRAMFILES%\\SumatraPDF"), os.path.expandvars("%ProgramW6432%\\SumatraPDF"), os.path.expandvars("%PROGRAMFILES(x86)%\\SumatraPDF") ] for path in paths: if os.path.exists(path): exe = os.path.join(path, 'SumatraPDF.exe') if os.path.exists(exe): SumatraViewer._sumatra_exe = exe return exe return None
def find_binary(self, stata_fn): # 1) If provided a filename, try it first if binary_exists(stata_fn): return stata_fn # 2) Search Stata in registry reg = winreg.ConnectRegistry(None, winreg.HKEY_CLASSES_ROOT) keys = (r"Stata15Do\shell\open\command", r"Stata14Do\shell\open\command", r"Stata13Do\shell\open\command", r"Applications\StataMP-64.exe\shell\open\command", r"Applications\StataMP64.exe\shell\open\command") for key in keys: try: print('[Stata] looking for registry key:', key) key = winreg.OpenKey(reg, key) fn = winreg.QueryValue(key, None).strip('"').split('"')[0] if binary_exists(fn): print(" - key found, filename:", fn) return fn except: print(" - key not found, searching more...", key) pass # 3) Try filenames listed by hand extra = ('C:/Bin/Stata14/StataMP-64.exe', ) for fn in extra: if binary_exists(fn): return fn raise Exception('Stata binary not found')
def getGenerateScript(self): # Under Windows, GenerateProjectFiles.bat only exists for source builds of the engine batFile = self.getEngineRoot( ) + '\\Engine\\Build\\BatchFiles\\GenerateProjectFiles.bat' if os.path.exists(batFile): return batFile # For versions of the engine installed using the launcher, we need to query the shell integration # to determine the location of the Unreal Version Selector executable, which generates VS project files try: key = winreg.OpenKey( winreg.HKEY_CLASSES_ROOT, 'Unreal.ProjectFile\\shell\\rungenproj\\command') if key: command = winreg.QueryValue(key, None) if len(command) > 0: # Write the command to run UnrealVersionSelector.exe to our own batch file customBat = os.path.join(self._customBatchScriptDir(), 'GenerateProjectFiles.bat') Utility.writeFile(customBat, command.replace('"%1"', '%1') + '\r\n') return customBat except: pass raise UnrealManagerException( 'could not detect the location of GenerateProjectFiles.bat or UnrealVersionSelector.exe.\nThis typically indicates that .uproject files are not correctly associated with UE4.' )
def get_seabird_datacnv(self): seabird_utils_dir = get_setting_string("Seacat/DataCNV", '') if seabird_utils_dir: seabird_utils_exe = os.path.join(seabird_utils_dir, "datcnvw.exe") if not os.path.exists(seabird_utils_exe): seabird_utils_exe = "" else: seabird_utils_exe = "" if not seabird_utils_exe: try: rootkey = winreg.HKEY_CLASSES_ROOT xmlconkey = winreg.CreateKey(rootkey, "xmlconFile\\shell\\edit\\command") xmlcon_val = winreg.QueryValue(xmlconkey, "") path_to_seabird_exe = xmlcon_val[:xmlcon_val.lower().find(".exe") + 4].replace("'", "").replace('"', "") seabird_utils_exe = os.path.join(os.path.dirname(path_to_seabird_exe), "datcnvw.exe") if seabird_utils_exe: if not os.path.exists(seabird_utils_exe): raise Exception("datcnv not found - asking user to supply location") except Exception: seabird_utils_exe = self.lib.cb.ask_filename(saving=False, key_name="Seacat/DataCNV", title="Find the Seabird Data Processing executable", file_filter="DataCNVw.exe|datcnvw.exe") # rcode, seabird_utils_dir = RegistryHelpers.GetDirFromUser(None, RegistryKey="UserSpecifiedSeabird", # Title="Find the Seabird Data Processing executable", # bLocalMachine=0, DefaultVal="", # Message="Plese locate the seabird data processing directory.\n" # "It's probably under Program files(x86).") return seabird_utils_exe
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 main(argv): s = argv[1] s = s.split() s = list(map(int, s)) s = byte(s) s = b''.join(s) s = s.decode('utf-16') arg_list = json.loads(s) try: subprocess.call(arg_list) except FileNotFoundError: app = arg_list[0] # Only the name of the python script is given. app = which(app)[0] ext = app.suffix prog = winreg.QueryValue(winreg.HKEY_CLASSES_ROOT, ext) comkey = winreg.OpenKey(winreg.HKEY_CLASSES_ROOT, rf'\{prog}\Shell\Open\Command') try: comstr = winreg.QueryValueEx(comkey, '')[0] items = re.findall(r'"[^"]+"|\S+', comstr) finally: winreg.CloseKey(comkey) new_list = [items[0].replace('"', '')] for item in items[1:]: item = item.replace('"', '') if item == '%1': new_list.append(str(app)) elif item == '%*': new_list.extend(arg_list[1:]) else: new_list.append(item) subprocess.call(new_list)
def GetLatestRobloxExe(self): reg = winreg.ConnectRegistry(None, winreg.HKEY_CLASSES_ROOT) key = winreg.OpenKey(reg, "roblox-player\\DefaultIcon") location = winreg.QueryValue(key, '').replace('RobloxPlayerLauncher', 'RobloxPlayerBeta') winreg.CloseKey(key) return location
def caminho_chrome(self): result = None if winreg: for subkey in [ "ChromeHTML\\shell\\open\\command", "Applications\\chrome.exe\\shell\\open\\command" ]: try: result = winreg.QueryValue(winreg.HKEY_CLASSES_ROOT, subkey) except WindowsError: pass if result is not None: result_split = shlex.split(result, False, True) result = result_split[0] if result_split else None if os.path.isfile(result): break result = None else: expected = "google-chrome" + (".exe" if os.name == "nt" else "") for parent in os.environ.get("PATH", "").split(os.pathsep): path = os.path.join(parent, expected) if os.path.isfile(path): result = path break return result
def find_chrome_win(): #using edge by default since it's build on chromium edge_path = "C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe" if os.path.exists(edge_path): return edge_path import winreg as reg reg_path = r'SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\chrome.exe' chrome_path = None last_exception = None for install_type in reg.HKEY_CURRENT_USER, reg.HKEY_LOCAL_MACHINE: try: reg_key = reg.OpenKey(install_type, reg_path, 0, reg.KEY_READ) chrome_path = reg.QueryValue(reg_key, None) reg_key.Close() except WindowsError as e: last_exception = e else: if chrome_path and len(chrome_path) > 0: break # Only log some debug info if we failed completely to find chrome if not chrome_path: logging.exception(last_exception) logging.error("Failed to detect chrome location from registry") else: logging.info(f"Chrome path detected as: {chrome_path}") return chrome_path
def Install(menu_name='This is the name that shows up in the context menu.'): '''Install registry entry for adding to context menu.''' import winreg as wr for ext in ['.pdf']: # Check for extension handler override try: override = wr.QueryValue(wr.HKEY_CLASSES_ROOT, ext) if override: ext = override except WindowsError: pass #endtry keyVal = ext + '\\Shell\\' + menu_name + '\\command' print(keyVal) try: key = wr.OpenKey(wr.HKEY_CLASSES_ROOT, keyVal, 0, wr.KEY_ALL_ACCESS) except WindowsError: key = wr.CreateKey(wr.HKEY_CLASSES_ROOT, keyVal) regEntry = ( r'"C:/Users/xuzew/AppData/Local/Programs/Python/Python37/python.exe" "' + r'"d:/Code/devops/pdf-del-first-page.py" "%1"') #wr.SetValueEx(key, '', 0, wr.REG_SZ, regEntry) print(key) print(regEntry) wr.CloseKey(key)
def get_exe_path(): reg = winreg.ConnectRegistry(None, winreg.HKEY_CLASSES_ROOT) subkeys = [ r"Applications\StataMP64.exe\shell\open\command", r"Applications\StataMP-64.exe\shell\open\command", r"Stata12Data\shell\open\command" ] key_found = False for subkey in subkeys: try: key = winreg.OpenKey(reg, subkey) fn = winreg.QueryValue(key, None).strip('"').split('"')[0] key_found = True except: #print("StataEditor: key not found, searching more;", subkey) pass if key_found: break else: print("StataEditor: Couldn't find Stata path") settings_fn = 'StataEditor.sublime-settings' settings = sublime.load_settings(settings_fn) fn = settings.get('stata_path', settings.get('stata_path_old', '')) return fn
def getSoftwareInstallPath(self, major_version): regpath = "{}\shell\open\command".format(self.getVersionedServiceName(major_version)) sldwks_exe = winreg.QueryValue(winreg.HKEY_CLASSES_ROOT, regpath) sldwks_exe = sldwks_exe.split()[0] sldwks_exe = convertDosPathIntoLongPath(sldwks_exe) sldwkd_inst = os.path.split(sldwks_exe)[0] return sldwkd_inst
def find_chrome_win(): import winreg as reg reg_path = r'SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\chrome.exe' chrome_path = None last_exception = None for install_type in reg.HKEY_CURRENT_USER, reg.HKEY_LOCAL_MACHINE: try: reg_key = reg.OpenKey(install_type, reg_path, 0, reg.KEY_READ) chrome_path = reg.QueryValue(reg_key, None) reg_key.Close() except WindowsError as e: last_exception = e else: if chrome_path and len(chrome_path) > 0: break # Only log some debug info if we failed completely to find chrome if not chrome_path: log.exception(last_exception) log.error("Failed to detect chrome location from registry") else: log.debug(f"Chrome path detected as: {chrome_path}") return chrome_path
def get_anybodycon_path(): """Return the path to default AnyBody console application.""" if not ON_WINDOWS: return None try: import winreg except ImportError: import _winreg as winreg try: abpath = winreg.QueryValue(winreg.HKEY_CLASSES_ROOT, 'AnyBody.AnyScript\shell\open\command') except WindowsError: raise WindowsError('Could not locate AnyBody in registry') abpath = abpath.rsplit(' ', 1)[0].strip('"') abpath = os.path.join(os.path.dirname(abpath), 'AnyBodyCon.exe') if not os.path.isfile(abpath): raise IOError( ("Registry path (%s) to AnyBody console leads to non-existing file. " "Set anybodycon_path in AnyPyProcess() to manually set the path." ) % abpath) if '~' in abpath: abpath = _expand_short_path_name(abpath) return abpath
def _get_interpreters_from_windows_registry(self): # https://github.com/python/cpython/blob/master/Tools/msi/README.txt import winreg result = set() for key in [winreg.HKEY_LOCAL_MACHINE, winreg.HKEY_CURRENT_USER]: for version in [ "3.5", "3.5-32", "3.5-64", "3.6", "3.6-32", "3.6-64", "3.7", "3.7-32", "3.7-64", "3.8", "3.8-32", "3.8-64", ]: try: for subkey in [ "SOFTWARE\\Python\\PythonCore\\" + version + "\\InstallPath", "SOFTWARE\\Python\\PythonCore\\Wow6432Node\\" + version + "\\InstallPath", ]: dir_ = winreg.QueryValue(key, subkey) if dir_: path = os.path.join(dir_, WINDOWS_EXE) if os.path.exists(path): result.add(path) except Exception: pass return result
def find_cmake(requirement): with winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE) as root: # Enumerate Kitware products to find installed CMake versions. versions = [] with winreg.OpenKey(root, 'SOFTWARE\\Kitware') as key: for i in itertools.count(): try: product = winreg.EnumKey(key, i) if product.startswith('CMake'): versions.append(product.split(' ', 1)[1]) except WindowsError as error: if error.errno != 22: raise break # Select a version that matches the desired constraints. version = select_version(requirement, versions) if not version: sys.stderr.write('No installed CMake version matches "%s".' % requirement) return None # Find the path to the selected version. try: path = 'SOFTWARE\\Kitware\\CMake ' + version with winreg.OpenKey(root, path) as key: cmake_path = winreg.QueryValue(key, '') except WindowsError as error: if error.errno != 2: raise sys.stderr.write('CMake "%s" not installed.' % version) return None # Return the path to the caller. return cmake_path
def windows(self): import winreg versionList = [] # Open base key regkeys = (winreg.HKEY_CURRENT_USER, winreg.HKEY_LOCAL_MACHINE) for regkey in regkeys: base = winreg.ConnectRegistry(None, regkey) try: key = winreg.OpenKey(base, 'SOFTWARE\\Python\\PythonCore', 0, winreg.KEY_READ) break except: exc_type, exc_value, exc_traceback = sys.exc_info() logging.error( repr( traceback.format_exception(exc_type, exc_value, exc_traceback))) if key is not None: # Get info about subkeys nsub, nval, modified = winreg.QueryInfoKey(key) # Query Python versions from registry for i in range(nsub): try: # Get name and subkey name = winreg.EnumKey(key, i) subkey = winreg.OpenKey(key, name + '\\InstallPath', 0, winreg.KEY_READ) # Get install location and store location = winreg.QueryValue(subkey, '') versionList.append(os.path.normpath(location)) # Close winreg.CloseKey(subkey) except: exc_type, exc_value, exc_traceback = sys.exc_info() logging.error( repr( traceback.format_exception(exc_type, exc_value, exc_traceback))) # Close keys winreg.CloseKey(key) winreg.CloseKey(base) # Query Python versions from file system for rootname in ['C:/', 'C:/Program Files', 'C:/Program Files (x86)']: if not os.path.isdir(rootname): continue for dir_item in os.listdir(rootname): if dir_item.lower().startswith('python'): path = os.path.normpath(os.path.join(rootname, dir_item)) if path not in versionList: versionList.append(path) for path in versionList: yield path
def RegisterPythonServer(filename, progids=None, verbose=0): if progids: if isinstance(progids, str): progids = [progids] # we know the CLSIDs we need, but we might not be an admin user # and otherwise unable to register them. So as long as the progids # exist and the DLL points at our version, assume it already is. why_not = None for progid in progids: try: clsid = pythoncom.MakeIID(progid) except pythoncom.com_error: # no progid - not registered. break # have a CLSID - open it. try: HKCR = winreg.HKEY_CLASSES_ROOT hk = winreg.OpenKey(HKCR, "CLSID\\%s" % clsid) dll = winreg.QueryValue(hk, "InprocServer32") except WindowsError: # no CLSID or InProcServer32 - not good! break ok_files = [os.path.basename(pythoncom.__file__), 'pythoncomloader%d%d.dll' % (sys.version_info[0], sys.version_info[1])] if os.path.basename(dll) not in ok_files: why_not = "%r is registered against a different Python version (%s)" % (progid, dll) break else: #print "Skipping registration of '%s' - already registered" % filename return # needs registration - see if its likely! try: from win32com.shell.shell import IsUserAnAdmin except ImportError: print("Can't import win32com.shell - no idea if you are an admin or not?") is_admin = False else: try: is_admin = IsUserAnAdmin() except pythoncom.com_error: # old, less-secure OS - assume *is* admin. is_admin = True if not is_admin: msg = "%r isn't registered, but I'm not an administrator who can register it." % progids[0] if why_not: msg += "\n(registration check failed as %s)" % why_not # throw a normal "class not registered" exception - we don't report # them the same way as "real" errors. raise pythoncom.com_error(winerror.CO_E_CLASSSTRING, msg, None, -1) # so theoretically we are able to register it. cmd = '%s "%s" --unattended > nul 2>&1' % (win32api.GetModuleFileName(0), filename) if verbose: print("Registering engine", filename) # print cmd rc = os.system(cmd) if rc: print("Registration command was:") print(cmd) raise RuntimeError("Registration of engine '%s' failed" % filename)
def get_default_windows_app(suffix): class_root = winreg.QueryValue(winreg.HKEY_CLASSES_ROOT, suffix) with winreg.OpenKey( winreg.HKEY_CLASSES_ROOT, r'{}\shell\open\command'.format(class_root)) as key: command = winreg.QueryValueEx(key, '')[0] return command.split(' ')[0]
def GetRegistryCommand(self, cmd, prjPath): '''Reads the Windows Registry to get the command string for the given command. cmd is one of 'open', 'run', 'rungenprog'.''' assert cmd in ['open', 'run', 'rungenproj'] with winreg.OpenKey(winreg.HKEY_CLASSES_ROOT, r'Unreal.ProjectFile\shell\%s\command' % cmd) as h: cmd = winreg.QueryValue(h, None) assert '%1' in cmd, cmd return cmd.replace('%1', os.path.abspath(prjPath))
def associated_application(ext): """ Scan the registry to find the application associated to a given file extension. """ try: file_class = winreg.QueryValue(winreg.HKEY_CLASSES_ROOT, ext) or ext action = winreg.QueryValue(winreg.HKEY_CLASSES_ROOT, file_class + '\\shell') or 'open' assoc_key = winreg.OpenKey( winreg.HKEY_CLASSES_ROOT, file_class + '\\shell\\' + action + '\\command') open_command = winreg.QueryValueEx(assoc_key, None)[0] # We assume a value `similar to '<command> %1 %2' return expand_env_vars(parse_line(open_command)[0]) except WindowsError as e: return None