def getHomePath(): """ Find the user home path. Note: If you are looking for MakeHuman data, you probably want getPath()! """ # Cache the home path global __home_path if __home_path is not None: return __home_path # Windows if sys.platform == 'win32': import _winreg keyname = r'Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders' #name = 'Personal' k = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER, keyname) value, type_ = _winreg.QueryValueEx(k, 'Personal') if type_ == _winreg.REG_EXPAND_SZ: __home_path = formatPath(_winreg.ExpandEnvironmentStrings(value)) return __home_path elif type_ == _winreg.REG_SZ: __home_path = formatPath(value) return __home_path else: raise RuntimeError("Couldn't determine user folder") # Unix-based else: __home_path = pathToUnicode(os.path.expanduser('~')) return __home_path
def expand_path(envpath): print "Expanded:" all=_winreg.ExpandEnvironmentStrings(envpath) array=all.split(";"); array.sort(); for key in array: print key;
def expandvars(var): """Expand environment variables. Return the argument with environment variables expanded. Substrings of the form $name or ${name} or %name% are replaced by the value of environment variable name.""" if isinstance(var, str): final = var.decode('utf-8') else: final = var if 'posix' == os.name: final = os.path.expandvars(final) elif 'nt' == os.name: import _winreg if final.startswith('${'): final = re.sub(r'\$\{(.*?)\}(?=$|\\)', lambda x: '%%%s%%' % x.group(1), final) elif final.startswith('$'): final = re.sub(r'\$(.*?)(?=$|\\)', lambda x: '%%%s%%' % x.group(1), final) final = _winreg.ExpandEnvironmentStrings(final) return final
def expandvars(var): """Expand environment variables. Return the argument with environment variables expanded. Substrings of the form $name or ${name} or %name% are replaced by the value of environment variable name.""" if isinstance(var, str): try: final = var.decode('utf-8') except UnicodeDecodeError: # Keep a string which won't be expanded under Windows 7. final = var else: final = var if 'posix' == os.name: final = os.path.expandvars(final) elif 'nt' == os.name: import _winreg if final.startswith('${'): final = re.sub(r'\$\{(.*?)\}(?=$|\\)', lambda x: '%%%s%%' % x.group(1), final) elif final.startswith('$'): final = re.sub(r'\$(.*?)(?=$|\\)', lambda x: '%%%s%%' % x.group(1), final) try: final = _winreg.ExpandEnvironmentStrings(final) except TypeError: # An error occurs when filename contains invalid # char and we return string instead of unicode. # This can happen on win7. pass return final
def _query(subKey): import _winreg key = _winreg.OpenKey( _winreg.HKEY_CURRENT_USER, "Software\\Microsoft\\Windows\\CurrentVersion" "\\Explorer\\User Shell Folders") val, _ = _winreg.QueryValueEx(key, subKey) return _winreg.ExpandEnvironmentStrings(val)
def getPath(type): if isinstance(type, (str, unicode)): typeStr = str(type) elif type is None: typeStr = "" else: raise TypeError("String expected") if sys.platform == 'win32': keyname = r'Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders' name = 'Personal' k = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER, keyname) value, type = _winreg.QueryValueEx(k, 'Personal') if type == _winreg.REG_EXPAND_SZ: path = _winreg.ExpandEnvironmentStrings(value) elif type == _winreg.REG_SZ: path = value else: raise RuntimeError("Couldn't determine user folder") if typeStr == "exports": path += u"\\makehuman\\exports\\" elif typeStr == "models": path += u"\\makehuman\\models\\" elif typeStr == "grab": path += u"\\makehuman\\grab\\" elif typeStr == "render": path += u"\\makehuman\\render\\" elif typeStr == "scenes": path += u"\\makehuman\\scenes\\" elif typeStr == "": path += u"\\makehuman\\" else: raise ValueError("Unknown value '%s' for getPath()!" % typeStr) else: path = os.path.expanduser('~') if sys.platform.startswith("darwin"): path = os.path.join(path, "Documents") path = os.path.join(path, "MakeHuman") else: path = os.path.join(path, "makehuman") if typeStr == "exports": path += "/exports/" elif typeStr == "models": path += "/models/" elif typeStr == "grab": path += "/grab/" elif typeStr == "render": path += "/render/" elif typeStr == "scenes": path += "/scenes/" elif typeStr == "": path += "/" else: raise ValueError("Unknown property '%s' for getPath()!" % typeStr) return path
def cmd_list(): vals = reg_get() if not vals: return print('-' * 42) for i, v in enumerate(vals): if '%' in v: print '%d. %s=>%s' % (i, v, win.ExpandEnvironmentStrings(v)) else: print '%d. %s' % (i, v) print('=' * 42)
def main(): paths, envpath = modify() if len(paths) > 1: print "Path(s) added:" print '\n'.join(paths[1:]) else: print "No path was added" print "\nPATH is now:\n%s\n" % envpath print "Expanded:" print _winreg.ExpandEnvironmentStrings(envpath)
def init_shell_folder(self): """ Get Shell Folders path from registry Only for Windows """ self.shell_folder = dict({}) key = _winreg.OpenKey( _winreg.HKEY_CURRENT_USER, 'Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\User Shell Folders', 0, _winreg.KEY_READ) for one in self.shell_key: (valeur, typevaleur) = _winreg.QueryValueEx(key, "Desktop") self.shell_folder[one] = _winreg.ExpandEnvironmentStrings(valeur) _winreg.CloseKey(key)
def addRegistryTypeLibs(self, locales=["0", "9"], arch="win32"): hive = _winreg.ConnectRegistry(None, _winreg.HKEY_CLASSES_ROOT) key = _winreg.OpenKey(hive, "Typelib") nLibs, d, d = _winreg.QueryInfoKey(key) #foreach typelib GUID for nLibNum in xrange(0, nLibs): #get the current typelib curLib = _winreg.EnumKey(key, nLibNum) tkey = _winreg.OpenKey(hive, "Typelib\\%s" % curLib) nVersions, d, d = _winreg.QueryInfoKey(tkey) #foreach version for nVerNum in xrange(0, nVersions): try: curVersion = _winreg.EnumKey(tkey, nVerNum) versKey = _winreg.OpenKey( hive, "TypeLib\\%s\\%s" % (curLib, curVersion)) lcKey = None #try to open each locale in our list for locale in locales: try: lcKey = _winreg.OpenKey(hive, "Typelib\\%s\\%s\\%s\\%s" % \ (curLib, curVersion, locale, arch)) val = _winreg.QueryValueEx(lcKey, "")[0] # tlbFile = _winreg.ExpandEnvironmentStrings(val) try: tEntry = typeLib(tlbFile) self.addLib(tEntry) except (OSError, pythoncom.com_error): pass _winreg.CloseKey(lcKey) break except WindowsError: if lcKey: _winreg.CloseKey(lcKey) continue _winreg.CloseKey(versKey) except WindowsError, exc: print "Unexpected end of typelib version list %s, error %s" % ( guid, exc.strerror) raise
def main(): python_path = os.path.dirname(os.path.normpath(sys.executable)) scripts = os.path.join(python_path, "Scripts") with winreg.CreateKey(HKLM, ENV) as key: for variable_name in ("PATH", "PYTHONPATH"): paths, envpath = modify_env(key, variable_name, (python_path, scripts)) if len(paths) > 1: print "Path(s) added:" print '\n'.join(paths[1:]) else: print "No path was added" print "\n%s is now:\n%s\n" % (variable_name, envpath) print "Expanded:" print winreg.ExpandEnvironmentStrings(envpath) print "PYTHONHOME: %s" % python_path winreg.SetValueEx(key, "PYTHONHOME", 0, winreg.REG_EXPAND_SZ, python_path)
def __str__(self): if self.type == _winreg.REG_EXPAND_SZ: value = self.value if type(value) is not unicode: try: value = value.decode(sys.getfilesystemencoding()) except UnicodeDecodeError: value = value.decode('latin1') try: return _winreg.ExpandEnvironmentStrings(value) except TypeError: pass return value elif self.type == _winreg.REG_SZ: return self.value return str(self.value)
def fix_winpython_pathenv(): """ Add Python & Python Scripts to the search path on Windows """ import ctypes from ctypes.wintypes import HWND, UINT, WPARAM, LPARAM, LPVOID try: import _winreg as winreg except ImportError: import winreg # took these lines from the native "win_add2path.py" pythonpath = os.path.dirname(CURINTERPRETER_PATH) scripts = os.path.join(pythonpath, "Scripts") if not os.path.isdir(scripts): os.makedirs(scripts) with winreg.CreateKey(winreg.HKEY_CURRENT_USER, u"Environment") as key: try: envpath = winreg.QueryValueEx(key, u"PATH")[0] except WindowsError: envpath = u"%PATH%" paths = [envpath] for path in (pythonpath, scripts): if path and path not in envpath and os.path.isdir(path): paths.append(path) envpath = os.pathsep.join(paths) winreg.SetValueEx(key, u"PATH", 0, winreg.REG_EXPAND_SZ, envpath) winreg.ExpandEnvironmentStrings(envpath) # notify the system about the changes SendMessage = ctypes.windll.user32.SendMessageW SendMessage.argtypes = HWND, UINT, WPARAM, LPVOID SendMessage.restype = LPARAM SendMessage(0xFFFF, 0x1A, 0, u"Environment") return True
def origin(self): import _winreg for i in range(len(self.regValues)): if self.regTerm[i] == 'start' or self.regTerm[i] == 'delete': continue value = self.regValues[i] term = self.regTerm[i] try: # Absolute path exists, but must be extracted if value.value_type() == Registry.RegSZ: # Drive letter start = value.value().index(':') - 1 if 'A' > value.value()[start] or 'Z' < value.value( )[start]: continue # end of substring for extension end = value.value().index(term) + 4 if start > end: continue path = value.value()[start:end] self.virusTotalReport(path, value.name(), value.value()) # Relative path if value.value_type() == Registry.RegExpandSZ: start = value.value().index('%') end = value.value().index(term) + 4 # Get absolute path and get report expanded = unicode(value.value()[start:end]) path = str(_winreg.ExpandEnvironmentStrings(expanded)) self.virusTotalReport(path, value.name(), value.value()) except: pass
def getNookLogFiles(): logFiles = [] found = False if iswindows: import _winreg as winreg # some 64 bit machines do not have the proper registry key for some reason # or the python interface to the 32 vs 64 bit registry is broken paths = set() if 'LOCALAPPDATA' in os.environ.keys(): # Python 2.x does not return unicode env. Use Python 3.x path = winreg.ExpandEnvironmentStrings(u"%LOCALAPPDATA%") if os.path.isdir(path): paths.add(path) if 'USERPROFILE' in os.environ.keys(): # Python 2.x does not return unicode env. Use Python 3.x path = winreg.ExpandEnvironmentStrings( u"%USERPROFILE%") + u"\\AppData\\Local" if os.path.isdir(path): paths.add(path) path = winreg.ExpandEnvironmentStrings( u"%USERPROFILE%") + u"\\AppData\\Roaming" if os.path.isdir(path): paths.add(path) # User Shell Folders show take precedent over Shell Folders if present try: regkey = winreg.OpenKey( winreg.HKEY_CURRENT_USER, "Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\User Shell Folders\\" ) path = winreg.QueryValueEx(regkey, 'Local AppData')[0] if os.path.isdir(path): paths.add(path) except WindowsError: pass try: regkey = winreg.OpenKey( winreg.HKEY_CURRENT_USER, "Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\User Shell Folders\\" ) path = winreg.QueryValueEx(regkey, 'AppData')[0] if os.path.isdir(path): paths.add(path) except WindowsError: pass try: regkey = winreg.OpenKey( winreg.HKEY_CURRENT_USER, "Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders\\" ) path = winreg.QueryValueEx(regkey, 'Local AppData')[0] if os.path.isdir(path): paths.add(path) except WindowsError: pass try: regkey = winreg.OpenKey( winreg.HKEY_CURRENT_USER, "Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders\\" ) path = winreg.QueryValueEx(regkey, 'AppData')[0] if os.path.isdir(path): paths.add(path) except WindowsError: pass for path in paths: # look for nookStudy log file logpath = path + '\\Barnes & Noble\\NOOKstudy\\logs\\BNClientLog.txt' if os.path.isfile(logpath): found = True print('Found nookStudy log file: ' + logpath.encode('ascii', 'ignore')) logFiles.append(logpath) else: home = os.getenv('HOME') # check for BNClientLog.txt in various locations testpath = home + '/Library/Application Support/Barnes & Noble/DesktopReader/logs/BNClientLog.txt' if os.path.isfile(testpath): logFiles.append(testpath) print('Found nookStudy log file: ' + testpath) found = True testpath = home + '/Library/Application Support/Barnes & Noble/DesktopReader/indices/BNClientLog.txt' if os.path.isfile(testpath): logFiles.append(testpath) print('Found nookStudy log file: ' + testpath) found = True testpath = home + '/Library/Application Support/Barnes & Noble/BNDesktopReader/logs/BNClientLog.txt' if os.path.isfile(testpath): logFiles.append(testpath) print('Found nookStudy log file: ' + testpath) found = True testpath = home + '/Library/Application Support/Barnes & Noble/BNDesktopReader/indices/BNClientLog.txt' if os.path.isfile(testpath): logFiles.append(testpath) print('Found nookStudy log file: ' + testpath) found = True if not found: print('No nook Study log files have been found.') return logFiles
except WindowsError, exc: try: if key: _winreg.CloseKey(key) except WindowsError: pass # parse out the version number for use in finding typelib if self.version: major, minor = self.version.split(".") self.majorVers = int(major) self.minorVers = int(minor) #expand any environment variables in the path to binaries if self.InProcServer: self.InProcServer = _winreg.ExpandEnvironmentStrings( self.InProcServer) if self.LocalServer: self.LocalServer = _winreg.ExpandEnvironmentStrings( self.LocalServer) self.checkASLR() #parse the typelib, and add any new interfaces we can discover from it if self.version and self.typeLibCLSID: self.typeLibCLSID = self.typeLibCLSID.upper() self.tlb = self.tMan.getLib(self.typeLibCLSID, self.majorVers) if not self.tlb: pass """ print "WARNING: Can't find typelib file for %s major %d\n%s" % (self.typeLibCLSID,
def __init__(self, serials=[], device_path=None): print(__about__) self.kobodir = u"" kobodb = u"" # Order of checks # 1. first check if a device_path has been passed in, and whether # we can find the sqlite db in the respective place # 2. if 1., and we got some serials passed in (from saved # settings in calibre), just use it # 3. if 1. worked, but we didn't get serials, try to parse them # from the device, if this didn't work, unset everything # 4. if by now we don't have kobodir set, give up on device and # try to use the Desktop app. # step 1. check whether this looks like a real device if (device_path): # we got a device path self.kobodir = os.path.join(device_path, u".kobo") # devices use KoboReader.sqlite kobodb = os.path.join(self.kobodir, u"KoboReader.sqlite") if (not (os.path.isfile(kobodb))): # device path seems to be wrong, unset it device_path = u"" self.kobodir = u"" kobodb = u"" if (self.kobodir): # step 3. we found a device but didn't get serials, try to get them if (len(serials) == 0): # we got a device path but no saved serial # try to get the serial from the device # print u"get_device_settings - device_path = {0}".format(device_path) # get serial from device_path/.adobe-digital-editions/device.xml if can_parse_xml: devicexml = os.path.join(device_path, '.adobe-digital-editions', 'device.xml') # print u"trying to load {0}".format(devicexml) if (os.path.exists(devicexml)): # print u"trying to parse {0}".format(devicexml) xmltree = ET.parse(devicexml) for node in xmltree.iter(): if "deviceSerial" in node.tag: serial = node.text # print u"found serial {0}".format(serial) serials.append(serial) break else: # print u"cannot get serials from device." device_path = u"" self.kobodir = u"" kobodb = u"" if (self.kobodir == u""): # step 4. we haven't found a device with serials, so try desktop apps if sys.platform.startswith('win'): import _winreg as winreg if sys.getwindowsversion().major > 5: if 'LOCALAPPDATA' in os.environ.keys(): # Python 2.x does not return unicode env. Use Python 3.x self.kobodir = winreg.ExpandEnvironmentStrings( u"%LOCALAPPDATA%") if (self.kobodir == u""): if 'USERPROFILE' in os.environ.keys(): # Python 2.x does not return unicode env. Use Python 3.x self.kobodir = os.path.join( winreg.ExpandEnvironmentStrings(u"%USERPROFILE%"), u"Local Settings", u"Application Data") self.kobodir = os.path.join(self.kobodir, u"Kobo", u"Kobo Desktop Edition") elif sys.platform.startswith('darwin'): self.kobodir = os.path.join(os.environ['HOME'], u"Library", u"Application Support", u"Kobo", u"Kobo Desktop Edition") #elif linux_path != None: # Probably Linux, let's get the wine prefix and path to Kobo. # self.kobodir = os.path.join(linux_path, u"Local Settings", u"Application Data", u"Kobo", u"Kobo Desktop Edition") # desktop versions use Kobo.sqlite kobodb = os.path.join(self.kobodir, u"Kobo.sqlite") # check for existence of file if (not (os.path.isfile(kobodb))): # give up here, we haven't found anything useful self.kobodir = u"" kobodb = u"" if (self.kobodir != u""): self.bookdir = os.path.join(self.kobodir, u"kepub") # make a copy of the database in a temporary file # so we can ensure it's not using WAL logging which sqlite3 can't do. self.newdb = tempfile.NamedTemporaryFile(mode='wb', delete=False) print(self.newdb.name) olddb = open(kobodb, 'rb') self.newdb.write(olddb.read(18)) self.newdb.write('\x01\x01') olddb.read(2) self.newdb.write(olddb.read()) olddb.close() self.newdb.close() self.__sqlite = sqlite3.connect(self.newdb.name) self.__cursor = self.__sqlite.cursor() self._userkeys = [] self._books = [] self._volumeID = [] self._serials = serials
if not message: routes = [ (r'GET /(?P<path>.*)', do_get), (r'PUT /(?P<path>.*)', do_put), (r'POST /(?P<path>.*)', do_post), (r'DELETE /(?P<path>.*)', do_delete), ] else: routes = [ (r'GET /(?P<path>.*)', do_message), ] # Find the data in the home directory if sys.platform == 'win32': import _winreg home_config = _winreg.ExpandEnvironmentStrings(u'%APPDATA%\\Platane\\') else: home_config = os.path.expanduser("~" + getpass.getuser()) + '/.platane/' root = None home_root = home_config + "root" if os.path.exists(home_root): root = home_root model.root = root application = restlite.router(routes) # Starts a standalone instance if __name__ == '__main__': from wsgiref.simple_server import make_server console_handler = logging.StreamHandler(sys.stdout) formatter = logging.Formatter(
def _query(key, subKey): import _winreg val, _ = _winreg.QueryValueEx(key, subKey) return _winreg.ExpandEnvironmentStrings(val)