def _generate_pgpassfile(self): """ Generate the pgpass file with the parameters from the command line (db_host, db_user, db_password) Used because pg_dump and pg_restore can not accept the password on the command line. """ is_win32 = sys.platform == 'win32' if is_win32: filename = os.path.join(os.environ['APPDATA'], 'pgpass.conf') else: filename = os.path.join(os.environ['HOME'], '.pgpass') text_to_add = "%(db_host)s:*:*:%(db_user)s:%(db_password)s" % self.options if os.path.exists(filename): content = [x.strip() for x in file(filename, 'r').readlines()] if text_to_add in content: return fp = file(filename, 'a+') fp.write(text_to_add + "\n") fp.close() if is_win32: try: import _winreg except ImportError: _winreg = None x = _winreg.ConnectRegistry(None, _winreg.HKEY_LOCAL_MACHINE) y = _winreg.OpenKey( x, r"SYSTEM\CurrentControlSet\Control\Session Manager\Environment", 0, _winreg.KEY_ALL_ACCESS) _winreg.SetValueEx(y, "PGPASSFILE", 0, _winreg.REG_EXPAND_SZ, filename) _winreg.CloseKey(y) _winreg.CloseKey(x) else: import stat os.chmod(filename, stat.S_IRUSR + stat.S_IWUSR)
def main(): fdkPythonPath = os.path.abspath(os.path.dirname(__file__)) try: registry = _winreg.ConnectRegistry(None, _winreg.HKEY_LOCAL_MACHINE) key = r"SYSTEM\CurrentControlSet\Control\Session Manager\Environment" path = getRegistryValue(registry, key, "Path") path = removeOldFDKDirectories(path) path += ";" + fdkPythonPath print "Adding the AFDKO Python command home dir '%s' to the system environment variable PATH." % (fdkPythonPath) setRegistryValue(registry, key, "Path", path, _winreg.REG_EXPAND_SZ) print "Success." print "You now need to log off or restart; the AFDKO Python command '%s' will then work in a new command window." % (kAFDKOPythonName) except: print "Error", repr(sys.exc_info()[1]) if "Access" in repr(sys.exc_info()[1]): print "You need system admin privileges to run this script." else: print "You will have to manually add the path to the AFDKO Python command home directory to the system environment variable PATH." print "Quitting. Failed to add the AFDKO Python command home directory to the system environment variable PATH." return
def break_sopcast(): if xbmc.getCondVisibility('system.platform.windows'): import _winreg aReg = _winreg.ConnectRegistry(None, _winreg.HKEY_LOCAL_MACHINE) try: aKey = _winreg.OpenKey(aReg, r'SOFTWARE\SopCast\Player\InstallPath', 0, _winreg.KEY_READ) name, value, type = _winreg.EnumValue(aKey, 0) codec_file = os.path.join( os.path.join(value.replace("SopCast.exe", "")), 'codec', 'sop.ocx.old') _winreg.CloseKey(aKey) if xbmcvfs.exists(codec_file): xbmcvfs.rename( codec_file, os.path.join( os.path.join(value.replace("SopCast.exe", "")), 'codec', 'sop.ocx')) except: pass
def exists(env): """ Make sure this tool exists. """ print "CHECKING FOR GRAPHVIZ" if platform.system() == "Windows": try: import _winreg x = _winreg.ConnectRegistry(None, _winreg.HKEY_LOCAL_MACHINE) y = _winreg.OpenKey(x, HKLM_GRAPHVIZ) INCLUDE, t = _winreg.QueryValueEx(y, 'InstallPath') print "GRAPHVIZ EXISTS" return True except: print "GRAPHVIZ DOESN'T EXIST" return False else: print "NOT WINDOWS" if not subprocess.call('pkg-config libgvc libagraph --exists'): return True return False
def WriteSettings(self): import _winreg as wr aReg = wr.ConnectRegistry(None, wr.HKEY_LOCAL_MACHINE) targ = r'SOFTWARE\Microsoft\Windows\FlightPlannerLicense' print "*** Writing to", targ, "***" try: aKey = wr.OpenKey(aReg, targ, 0, wr.KEY_WRITE) except: aKey = wr.CreateKey(aReg, targ) try: try: wr.SetValueEx(aKey, "ProjectPath", 0, wr.REG_SZ, String.QString2Str(self.ProjectFolderPath)) except Exception: print "Encountered problems writing into the Registry..." except: print "NO" finally: wr.CloseKey(aKey) wr.CloseKey(aReg)
def _win_clear(self): import _winreg as Regedit regedit = Regedit.ConnectRegistry(None, Regedit.HKEY_LOCAL_MACHINE) try: tag = self.regedit_path key = Regedit.OpenKey(regedit, tag, 0, Regedit.KEY_WRITE) try: try: Regedit.SetValueEx(key, self.key_name, 0, Regedit.REG_SZ, self.exe_path) Regedit.DeleteValue(key, self.key_name) g_logger.info("Cancel Auto StartUP") except EnvironmentError: g_logger.error( "Cancel Auto StartUP Error in Windows (%s,%s)" % (tag, self.key_name)) raise finally: Regedit.CloseKey(key) finally: Regedit.CloseKey(regedit)
def list_networks_win(networks): """Windows shim for list_networks. Also go to the registry to get a friendly name""" reg = wr.ConnectRegistry(None, wr.HKEY_LOCAL_MACHINE) reg_key = wr.OpenKey( reg, r'SYSTEM\CurrentControlSet\Control\Network\{4D36E972-E325-11CE-BFC1-08002BE10318}' ) for key, val in networks.iteritems(): val['pcapname'] = '\\Device\\NPF_{}'.format(key) net_regkey = r'{}\Connection'.format(key) try: net_key = wr.OpenKey(reg_key, net_regkey) # Probably need to filter on MediaSubType here to only ask for ethernet net_name = wr.QueryValueEx(net_key, 'Name')[0] if net_name: val['name'] = net_name except WindowsError: #pylint: disable=E0602 pass wr.CloseKey(reg_key) return networks
def DetectVS(): aReg = winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE) try: aKey = winreg.OpenKey(aReg, REGISTRY_VS_ROOT) count = 0 while True: aSubKeyName = winreg.EnumKey(aKey, count) try: vs_prototype = find_first(VS_PROTOTYPES, lambda vs: vs.version == aSubKeyName) aSubKey = winreg.OpenKey(aKey, aSubKeyName) try: aSetupKey = winreg.OpenKey(aSubKey, REGISTRY_VS_SETUP) yield VS(name=vs_prototype.name, version=vs_prototype.version, setup=SetupVS(aSetupKey)) winreg.CloseKey(aSetupKey) except WindowsError: pass winreg.CloseKey(aSubKey) except StopIteration: pass count += 1 winreg.CloseKey(aKey) except WindowsError: pass winreg.CloseKey(aReg)
def spawnVLC(cmd, delay=0): try: if AceConfig.osplatform == 'Windows' and AceConfig.vlcuseaceplayer: import _winreg import os.path reg = _winreg.ConnectRegistry(None, _winreg.HKEY_CURRENT_USER) try: key = _winreg.OpenKey(reg, 'Software\AceStream') except: print "Can't find AceStream!" sys.exit(1) dir = _winreg.QueryValueEx(key, 'InstallDir') playerdir = os.path.dirname(dir[0] + '\\player\\') cmd[0] = playerdir + '\\' + cmd[0] stdout = None if AceConfig.loglevel == logging.DEBUG else DEVNULL stderr = None if AceConfig.loglevel == logging.DEBUG else DEVNULL AceStuff.vlc = psutil.Popen(cmd, stdout=stdout, stderr=stderr) gevent.sleep(delay) return True except: return False
def find_visual_studio_express(self, gen=None): if gen is None: gen = self._generator gen = gen.lower() try: import _winreg key_str = (r'SOFTWARE\Microsoft\VCEXpress\%s\Setup\VC' % self.gens[gen]['ver']) value_str = (r'ProductDir') print('Reading VS environment from HKEY_LOCAL_MACHINE\%s\%s' % (key_str, value_str)) print key_str reg = _winreg.ConnectRegistry(None, _winreg.HKEY_LOCAL_MACHINE) key = _winreg.OpenKey(reg, key_str) value = _winreg.QueryValueEx(key, value_str)[0] + "IDE" print 'Found: %s' % value return value except WindowsError, err: print >> sys.stderr, "Didn't find ", self.gens[gen]['gen'] return ''
def get_lib(name, cdll_opts = None): libname = None if OSNAME == "Linux": libname = "lib" + name + ".so" elif OSNAME == "Darwin": libname = "lib" + name + ".dylib" elif OSNAME == "Windows": import _winreg as wreg reg = wreg.ConnectRegistry(None, wreg.HKEY_LOCAL_MACHINE) key = wreg.OpenKey(reg, r"SOFTWARE\NVIDIA Corporation\Installed Products\NVIDIA CUDA") cuda_bin = os.path.join(wreg.QueryValueEx(key, "InstallDir")[0],"bin") libname = os.path.join(cuda_bin, "%s.dll" % name) if name == "cuda": libname = "nvcuda.dll" lib = ctypes.windll.LoadLibrary( libname ) return lib if cdll_opts: lib = ctypes.CDLL(libname, cdll_opts) else: lib = ctypes.CDLL(libname) return lib
def getPyCharmDebugEggPath(self, enableAutoDetect=False): # If path is defined in settings then use that settings = qt.QSettings() if settings.contains('Developer/PyCharmDebugEggPath'): pyCharmDebugEggPath = settings.value( 'Developer/PyCharmDebugEggPath') if self.isValidPyCharmDebugEggPath(pyCharmDebugEggPath): # found a good value in the settings return pyCharmDebugEggPath if not enableAutoDetect: return '' # Auto-detect import platform if platform.system() == 'Windows': import _winreg aReg = _winreg.ConnectRegistry(None, _winreg.HKEY_CLASSES_ROOT) aKey = _winreg.OpenKey( aReg, r"Applications\pycharm.exe\shell\open\command") value = _winreg.QueryValue( aKey, None ) # something like: 'C:\Program Files (x86)\JetBrains\PyCharm 4.5.4\bin\pycharm.exe "%1"' if not value: # PyCharm not found in registry return '' # remove bin\pycharm and anything after that pyCharmPath = value[:value.find(r"\bin\pycharm.exe")] pyCharmPath = value[:value.find(r"\bin\pycharm64.exe")] # remove leading " character if present if pyCharmPath[0] == "\"": pyCharmPath = pyCharmPath[1:] pyCharmDebugEggPath = pyCharmPath + r"\debug-eggs\pycharm-debug.egg" if self.isValidPyCharmDebugEggPath(pyCharmDebugEggPath): # found a good value in registry return pyCharmDebugEggPath # Not found return ''
def Get_User_ShellFolders(): # Routine to grab all the Windows Shell Folder locations from the registry. If successful, returns dictionary # of shell folder locations indexed on Windows keyword for each; otherwise, returns an empty dictionary. import _winreg return_dict = {} # First open the registry hive try: Hive = _winreg.ConnectRegistry(None, _winreg.HKEY_CURRENT_USER) except WindowsError: print "Can't connect to registry hive HKEY_CURRENT_USER." return return_dict # Then open the registry key where Windows stores the Shell Folder locations try: Key = _winreg.OpenKey( Hive, "Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders") except WindowsError: print "Can't open registry key Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders." _winreg.CloseKey(Hive) return return_dict # Nothing failed above, so enumerate through all the Shell Folder values and return in a dictionary # This relies on error at end of try: #i = 0 #while 1: for i in range(0, _winreg.QueryInfoKey(Key)[1]): name, value, val_type = _winreg.EnumValue(Key, i) return_dict[name] = value i += 1 _winreg.CloseKey(Key) # Only use with for loop _winreg.CloseKey(Hive) # Only use with for loop return return_dict # Only use with for loop except WindowsError: # In case of failure before read completed, don't return partial results _winreg.CloseKey(Key) _winreg.CloseKey(Hive) return {}
def iterRegistryUserDic(): """ @yield unicode the userdic prefix without ".dic" """ if not skos.WIN: return USERDIC_REG_PATH = r"SOFTWARE\Kodensha\jBeijing7\TransPad\JcUserDic" USERDIC_REG_KEY_I = r"User Dic%i" import _winreg for hk in _winreg.HKEY_CURRENT_USER, _winreg.HKEY_LOCAL_MACHINE: try: with _winreg.ConnectRegistry( None, hk) as reg: # computer_name = None with _winreg.OpenKey(reg, USERDIC_REG_PATH) as key: for i in 1, 2, 3: path = _winreg.QueryValueEx( key, USERDIC_REG_KEY_I % i)[0] if path: yield path except (WindowsError, TypeError, AttributeError): pass
def _win_set(self): import _winreg as Regedit regedit = Regedit.ConnectRegistry(None, Regedit.HKEY_LOCAL_MACHINE) try: tag = self.regedit_path key = Regedit.OpenKey(regedit, tag, 0, Regedit.KEY_WRITE) try: try: Regedit.SetValueEx(key, self.key_name, 0, Regedit.REG_SZ, self.exe_path) g_logger.info( "Auto StartUP icm-agent in Windows (%s,%s,%s)" % (tag, self.key_name, self.exe_path)) except EnvironmentError: g_logger.error( "Write Regedit key Error in Windows (%s,%s,%s)" % (tag, self.key_name, self.exe_path)) raise finally: Regedit.CloseKey(key) finally: Regedit.CloseKey(regedit)
def read(self, checkAllInterfaces=False): #first read in all registry related properties clsid = self.clsid valList = [ ("CLSID\\" + clsid + "\\", "", "defaultInfo"), ("CLSID\\" + clsid + "\\InProcServer32", "", "InProcServer"), ("CLSID\\" + clsid + "\\InProcServer32", "ThreadingModel", "inprocThreadingModel"), ("CLSID\\" + clsid + "\\LocalServer32", "", "LocalServer"), ("CLSID\\" + clsid + "\\LocalServer32", "ThreadingModel", "localThreadingModel"), ("CLSID\\" + clsid + "\\ProgID", "", "progID"), ("CLSID\\" + clsid + "\\TypeLib", "", "typeLibCLSID"), ("CLSID\\" + clsid + "\\Version", "", "version"), ("CLSID\\" + clsid + "\\VersionIndependentProgID", "", "indProgID"), ] hive = _winreg.ConnectRegistry(None, _winreg.HKEY_CLASSES_ROOT) # for vals in valList: try: # curKey = vals[0] curVal = vals[1] curProp = vals[2] key = None key = _winreg.OpenKey(hive, curKey) val = _winreg.QueryValueEx(key, curVal) setattr(self, curProp, val[0]) _winreg.CloseKey(key) except WindowsError, exc: try: if key: _winreg.CloseKey(key) except WindowsError: pass
def register_contextual_menu_win32(): """Register ndrive as a Windows explorer contextual menu entry""" import _winreg # TODO: better understand why / how this works. # See https://jira.nuxeo.com/browse/NXDRIVE-120 app_name = "None" args = " metadata --file \"%1\"" exe_path = find_exe_path() + args if exe_path is None: log.warning('Not a frozen windows exe: ' 'skipping startup application registration') return log.debug("Registering '%s' application %s to registry key %s", app_name, exe_path, REG_KEY) reg = _winreg.ConnectRegistry(None, _winreg.HKEY_CURRENT_USER) update_win32_reg_key( reg, REG_KEY, [(app_name, _winreg.REG_SZ, exe_path)], )
def register_contextual_menu(self): # TODO: better understand why / how this works. # See https://jira.nuxeo.com/browse/NXDRIVE-120 app_name = 'None' args = ' metadata --file "%1"' exe_path = self._manager.find_exe_path() + args if exe_path is None: return icon_path = self._manager.find_exe_path() + ',0' log.debug('Registering %r application %r to registry key %r', app_name, exe_path, self.get_menu_key()) reg = _winreg.ConnectRegistry(None, _winreg.HKEY_CURRENT_USER) self._update_reg_key( reg, self.get_menu_key(), [(app_name, _winreg.REG_SZ, exe_path)], ) self._update_reg_key( reg, self.get_menu_parent_key(), [("Icon", _winreg.REG_SZ, icon_path)], )
def get_win32_executable(): import _winreg reg = _winreg.ConnectRegistry(None, _winreg.HKEY_LOCAL_MACHINE) try: key = _winreg.OpenKey(reg, 'SOFTWARE\\VMware, Inc.\\VMware Workstation') try: return os.path.join( _winreg.QueryValueEx(key, 'InstallPath')[0], 'vmrun.exe') finally: _winreg.CloseKey(key) except WindowsError: key = _winreg.OpenKey( reg, 'SOFTWARE\\WOW6432Node\\VMware, Inc.\\VMware Workstation') try: return os.path.join( _winreg.QueryValueEx(key, 'InstallPath')[0], 'vmrun.exe') finally: _winreg.CloseKey(key) finally: reg.Close() return get_fallback_executable()
def get_arcgis_paths(): """ Use the windows registry to figure out the paths to the following folders: - bin - arcpy - scripts as subfolders of the installation directory. """ import _winreg registry = _winreg.ConnectRegistry(None, _winreg.HKEY_LOCAL_MACHINE) arcgis_version = get_arcgis_version() try: key = _winreg.OpenKey(registry, r"SOFTWARE\wow6432Node\ESRI\Desktop%s" % arcgis_version) except WindowsError: key = _winreg.OpenKey(registry, r"SOFTWARE\ESRI\Desktop%s" % arcgis_version) install_dir, _ = _winreg.QueryValueEx(key, 'InstallDir') paths = [os.path.join(install_dir, 'bin64'), os.path.join(install_dir, 'arcpy'), os.path.join(install_dir, 'scripts')] return paths
def enumRegKeySubkeys(self, key): """List all sub-keys of a specified key in the windows registry @param key: The registry key to check. The key should include the section. Eg. "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion" @type key: string """ hkey, key = self._getHiveAndKey(key) aReg = reg.ConnectRegistry(None, hkey) aKey = reg.OpenKey(aReg, key) result = [] index = 0 # The function EnumKey() retrieves the name of one subkey each time it is called. # It is typically called repeatedly, until an EnvironmentError exception # is raised, indicating no more values. while True: try: subkey = reg.EnumKey(aKey, index) result.append(subkey) index += 1 except EnvironmentError: return result
def printStudioInstalled(): # Check if we already know where Print Studio is global printStudioPath if printStudioPath is not None: return printStudioPath try: om.MGlobal.displayInfo( maya.stringTable['y_printStudio.kDetectPrintStudio']) if sys.platform.startswith('darwin'): # The bundle search is pretty slow, so see if Print Studio # is where we expect it # p = '/Applications/Autodesk/Autodesk Print Studio/Print Studio.app/Contents/MacOS/Print Studio' if not os.path.isfile(p): p = None cmd = 'mdfind kMDItemCFBundleIdentifier = "com.autodesk.spark.printstudio"' pipe = os.popen(cmd, 'r') while True: c = pipe.readline() if not c: break p = c if p is not None: p = os.path.join(p, 'Contents/MacOS/Print Studio') if p is not None: printStudioPath = p elif sys.platform.startswith('win'): aReg = _winreg.ConnectRegistry(None, _winreg.HKEY_LOCAL_MACHINE) aKey = _winreg.OpenKey( aReg, "SOFTWARE\\Autodesk\\{4B22C678-3E31-4E8E-BC6C-21C778D25420}") p = _winreg.QueryValueEx(aKey, "ExecPath") printStudioPath = p[0] except: pass return printStudioPath
def genGif(self): msg = QMessageBox() try: reg = _winreg.ConnectRegistry(None, _winreg.HKEY_LOCAL_MACHINE) k = _winreg.OpenKey(reg, r'SOFTWARE\ImageMagick\Current') pathName = os.path.join( _winreg.QueryValueEx(k, 'BinPath')[0], 'magick.exe') except (WindowsError): msg.setIcon(QMessageBox.Critical) msg = message['msg01'] msg.setWindowTitle(message['msg02']) msg.setText(message) msg.setStandardButtons(QMessageBox.Ok) msg.exec_() return None lapse = int(self.dlg.timeLapseEdit.text()) cmd = [ 'cmd', '/c', toUnicode(pathName).encode('big5'), 'convert', '-loop', '0', '-delay', str(lapse) + 'x1' ] for path in self.renderedLayerList: cmd.append(path) outName = self.dlg.outputNameEdit.text() + '.gif' cmd.append( toUnicode(os.path.join(self.workingFolder, outName)).encode('big5')) subprocess.call(cmd, shell=True) msg.setIcon(QMessageBox.Information) msg.setText(message['msg03']) msg.setWindowTitle(message['msg04']) msg.setStandardButtons(QMessageBox.Ok) msg.exec_()
def add_extension(self, *args): '''Add file extension(s) to %PATHEXT% system variable''' for ext in args: pathext = '' x = '' if isinstance(ext, list): for i in ext: System.add_extension(i) if isinstance(ext, str): try: x = reg.ConnectRegistry(None, LOCAL_MACHINE) pathKey = reg.OpenKey(x,\ self.keys.environment,\ 0,\ ALL_ACCESS) pathext = reg.QueryValueEx(pathKey, "pathext")[0] except: warn('Failed to open pathext reg key.') if '.' in ext: fileExt = ';' + ext.upper() else: fileExt = ';.' + ext.upper() if fileExt not in pathext: reg.SetValueEx(pathKey,\ 'pathext',\ 0,\ reg.REG_EXPAND_SZ,\ pathext + fileExt) pathext = reg.QueryValueEx(pathKey, "pathext")[0] if fileExt in pathext: pass else: warn('FAILED to add %s to \%PATHEXT\%.'%fileExt) else: pass if x: reg.CloseKey(pathKey) reg.CloseKey(x)
def test_registry_configuration(self): """ Test the configuration stored in the registry. """ import _winreg osi = self.manager_1.osi key = 'Software\\Nuxeo\\Drive' self.assertEqual(osi.get_system_configuration(), {}) self.addCleanup(osi._recursive_delete, _winreg.HKEY_CURRENT_USER, 'Software\\Nuxeo\\Drive') # Add new parameters reg = _winreg.ConnectRegistry(None, _winreg.HKEY_CURRENT_USER) osi._update_reg_key( reg, key, [('update-site-url', _winreg.REG_SZ, 'http://no.where')]) osi._update_reg_key( reg, key, [('update-BETA_site-url', _winreg.REG_SZ, 'http://no.where.beta')]) conf = osi.get_system_configuration() self.assertEqual(conf['update_site_url'], 'http://no.where') self.assertEqual(conf['update_beta_site_url'], 'http://no.where.beta')
def get_mime_type(path): ifile = gio.File(path) info = ifile.query_info(gio.FILE_ATTRIBUTE_STANDARD_CONTENT_TYPE) ext = info.get_content_type() reg = _winreg.ConnectRegistry(None, _winreg.HKEY_CLASSES_ROOT) subkey = _winreg.OpenKey(reg, "MIME\DataBase\Content Type") key_count, val_count, ldate = _winreg.QueryInfoKey(subkey) mimetype = '' for k in range(key_count): mime = _winreg.EnumKey(subkey, k) # if not mime.lower().startswith('image'): # continue mimekey = _winreg.OpenKey(subkey, mime) mimekey_count, mimeval_count, ldate = _winreg.QueryInfoKey( mimekey) for j in range(mimeval_count): mstr, value, vtype = _winreg.EnumValue(mimekey, j) if mstr == 'Extension' and value.lower() == ext.lower(): mimetype = mime break if mimetype == 'image/pjpeg': #windows defines a pjpeg for progressive jpeg, but all modern jpeg libs can open pjpeg, so no need to distinguish for our purposes mimetype = 'image/jpeg' return mimetype
def find_mysql_in_registry(): """Find MySQL Server installations in the Windows Registry. Connects to the Windows Registry and collects data from installations of MySQL Server. No guarantees are given that the installations reported are current, functional or to be found in the location given in the Registry. Returns a list of dictionary objects with keys 'Location' and 'Version'. The values are: for 'Location', the folder where the MySQL binaries are stored; for 'Version', a version string (actually, according to MySQL, a distribution string). If you need to find a particular installed version, use find_mysql_ver(major, minor). """ try: h = _winreg.ConnectRegistry(None, _winreg.HKEY_LOCAL_MACHINE) h = _winreg.OpenKey(h, r'SOFTWARE\MySQL AB') except WindowsError: return None i = 0 installations = [] while True: try: k = _winreg.EnumKey(h, i) if k.startswith('MySQL Server'): data = dict() h_ = _winreg.OpenKey(h, k) for vname in ('Location', 'Version'): v = _winreg.QueryValueEx(h_, vname) if v and len(v) == 2 and v[1] == _winreg.REG_SZ: data[vname] = v[0] installations.append(data) i += 1 except WindowsError: break return installations
def GetInstalledBrowsers(self): ''' usage:object.GetInstalledBrowsers() Output: browser_list-->list ''' path = 'SOFTWARE\Clients\StartMenuInternet' Hkeys = reg.HKEY_LOCAL_MACHINE Regkey = reg.ConnectRegistry(None, Hkeys) key = reg.OpenKey(Regkey, path, 0, reg.KEY_READ | reg.KEY_WOW64_32KEY) key_count = reg.QueryInfoKey(key)[0] browser = {} browser_list = [] for i in range(key_count): singsoft = {} try: keyname = reg.EnumKey(key, i) singsoft['id'] = i singsoft['Name'] = keyname browser_list.append(singsoft) except Exception as ex: continue return browser_list
def _get_desktop_path(self): """ HKEY_CURRENT_USER """ import _winreg desktop_path = "" aReg = _winreg.ConnectRegistry(None, _winreg.HKEY_CURRENT_USER) aKey = _winreg.OpenKey( aReg, r"Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders" ) try: val = _winreg.QueryValueEx(aKey, "Desktop") _logger.debug("reg key value:%s" % str(val)) desktop_path = str(val[0]) except EnvironmentError: print traceback.format_exc() print sys.exc_info()[0] return desktop_path
def register_contextual_menu(self): # TODO: better understand why / how this works. # See https://jira.nuxeo.com/browse/NXDRIVE-120 app_name = "None" args = " metadata --file \"%1\"" exe_path = self._manager.find_exe_path() + args if exe_path is None: log.warning('Not a frozen windows exe: ' 'skipping startup application registration') return icon_path = self._manager.find_exe_path() + ",0" log.debug("Registering '%s' application %s to registry key %s", app_name, exe_path, self.get_menu_key()) reg = _winreg.ConnectRegistry(None, _winreg.HKEY_CURRENT_USER) self._update_reg_key( reg, self.get_menu_key(), [(app_name, _winreg.REG_SZ, exe_path)], ) self._update_reg_key( reg, self.get_menu_parent_key(), [("Icon", _winreg.REG_SZ, icon_path)], )