コード例 #1
0
ファイル: getpath.py プロジェクト: yazici/makehuman-1
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

    alt_home_path = os.environ.get("MH_HOME_LOCATION", '')
    if os.path.exists(alt_home_path):
        __home_path = alt_home_path
            
    if __home_path is not None:
        return __home_path

    # Windows
    if sys.platform.startswith('win'):
        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
コード例 #2
0
ファイル: dns.py プロジェクト: tcztzy/sunshinesocks
    def _parse_hosts(self):
        self._hosts = {}
        if os.name == 'nt' and winreg is not None:
            subkey = r'SYSTEM\CurrentControlSet\Services\Tcpip\Parameters'
            with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, subkey) as params:
                data_base_path, _ = winreg.QueryValueEx(params, 'DataBasePath')
                base_path = winreg.ExpandEnvironmentStrings(data_base_path)
                hosts = Path(base_path, 'hosts')
        elif os.name == 'posix':
            hosts = Path('/etc/hosts')
        else:
            hosts = object()
            hosts.exists = lambda: False
        if hosts.exists():
            with hosts.open('rb') as f:
                for line in f.readlines():
                    line = line.strip()
                    parts = line.split()
                    if len(parts) < 2:
                        continue

                    ip = parts[0]
                    try:
                        ip_address(ip)
                    except ValueError:
                        continue

                    for i in range(1, len(parts)):
                        hostname = parts[i]
                        if hostname:
                            self._hosts[hostname] = ip
        else:
            self._hosts['localhost'] = '127.0.0.1'
コード例 #3
0
def main():
    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 sys.argv[1:]:
            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)
        print "Value set!"

    winreg.ExpandEnvironmentStrings(envpath)
    print "Expanded!"

    # notify the system about the changes
    SendMessage = ctypes.windll.user32.SendMessageW
    print 1
    SendMessage.argtypes = HWND, UINT, WPARAM, LPVOID
    print 2
    SendMessage.restype = LPARAM
    print 3
    SendMessage(0xFFFF, 0x1A, 0, u"Environment")
    print 4
    print "Message sent!"
コード例 #4
0
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))
コード例 #5
0
def setup_logging():
    """
    Removes all Loguru hooks, and adds the error log

    :return: nil
    """

    logger.remove()

    logpath = winreg.ExpandEnvironmentStrings("%appdata%\\ThomasPain\\ACARS\\logs")

    logger.add(logpath + "\\error.log", level="ERROR", rotation="5 MB")
コード例 #6
0
    def getenv_system(varname, default=''):
        import winreg

        v = default
        try:
            rkey = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE,
                                  'SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment')
            try:
                v = str(winreg.QueryValueEx(rkey, varname)[0])
                v = winreg.ExpandEnvironmentStrings(v)
            except:
                pass
        finally:
            winreg.CloseKey(rkey)
        return v
コード例 #7
0
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

    # The environment variable MH_HOME_LOCATION will supersede any other settings for the home folder.
    alt_home_path = os.environ.get("MH_HOME_LOCATION", '')
    if os.path.isdir(alt_home_path):
        __home_path = formatPath(alt_home_path)

    if __home_path is not None:
        return __home_path

    # Windows
    if sys.platform.startswith('win'):
        import winreg
        keyname = r'Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders'
        #name = 'Personal'
        with winreg.OpenKey(winreg.HKEY_CURRENT_USER, keyname) as k:
            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")

    # Linux
    elif sys.platform.startswith('linux'):
        doc_folder = XDG_PATHS.get('DOCUMENTS', '')
        if os.path.isdir(doc_folder):
            __home_path = doc_folder
        else:
            __home_path = pathToUnicode(os.path.expanduser('~'))

    # Darwin
    else:
        __home_path = os.path.expanduser('~')

    return __home_path
コード例 #8
0
    def get_value(self, name=None, default=None, expand=False):
        name = name or ''
        uni_name = reg_unicode(name)
        try:
            value, regtype = self.typed_values.get(uni_name)
        except TypeError:
            return default

        if expand:
            if regtype in (
                    'REG_SZ',
                    'REG_EXPAND_SZ',
            ):
                value = winreg.ExpandEnvironmentStrings(value)
            if regtype in ('REG_MULTI_SZ', ):
                value[:] = map(winreg.ExpandEnvironmentStrings, value)

        return value
コード例 #9
0
ファイル: primo.py プロジェクト: intelitrader/primo
        def add_parameter(name, attrs):
            if name == 'Parameter':
                value = self.EmbeddedCodeProcessor(attrs['value'])
            elif name == 'ParameterFromEnvironment':
                value = os.environ[attrs['varname']] if attrs[
                    'varname'] in os.environ else self.EmbeddedCodeProcessor(
                        attrs['default']) if 'default' in attrs else ''
            elif name == 'ParameterFromCommandLine':
                name = attrs['name']
                if name in self.cmdline_params:
                    value = self.cmdline_params[name]
                else:
                    value = attrs['default']
            elif name == 'ParameterFromRegistry':
                if sys.platform == 'win32':
                    k = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE,
                                        attrs['regkey'])
                    value = _winreg.QueryValueEx(k, attrs['regvalue'])[0]
                    value = _winreg.ExpandEnvironmentStrings(value)
                else:
                    print('WARNING: ParameterFromRegistry tag is support only on Windows, ' + \
                    "for obvious reasons. I\'m *ignoring* it.")
            else:
                # TODO: better error handling
                assert False and 'not a valid parameter element'

            # if it looks like a number, we'll assume it's a number
            parameter_type = attrs['type'] if 'type' in attrs else 'string'

            if parameter_type == 'string':
                pass
            elif parameter_type == 'int':
                value = int(value)
            elif parameter_type == 'float':
                value = float(value)
            else:
                raise Exception('Invalid parameter type: ', parameter_type)

            # parameters will be added to this dict which is used
            # as "globals" for every code run by primo
            self.globals[self.EmbeddedCodeProcessor(attrs['name'])] = value
コード例 #10
0
def set_env_var(name,
                value,
                regtype=winreg.REG_SZ,
                overwrite=True,
                env=ENV_SYSTEM):
    """Add new or overwrite existing environment variables"""

    if not name or len(name) < 1:
        raise ValueError("Invalid name value")

    if not value or len(value) < 1:
        raise ValueError("Invalid value")

    if regtype != winreg.REG_SZ and regtype != winreg.REG_EXPAND_SZ:
        raise ValueError("Invalid type")

    key = _get_reg_key(env, winreg.KEY_ALL_ACCESS)
    cval = None
    ctype = regtype

    try:
        cval, ctype = winreg.QueryValueEx(key, name)
    except WindowsError:
        pass

    if cval is None or overwrite:
        winreg.SetValueEx(key, name, 0, ctype, value)
        notify_env_change()

        if regtype == winreg.REG_EXPAND_SZ:
            os.environ[name] = text(winreg.ExpandEnvironmentStrings(value))
        else:
            os.environ[name] = text(value)

        winreg.CloseKey(key)
    else:
        winreg.CloseKey(key)
        raise EnvironmentError(
            'Environment variable {} already exists, but overwrite is false'.
            format(name))
コード例 #11
0
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 G.args.get("home_location") is not None:
        __home_path = formatPath(G.args.get("home_location"))
        if os.path.isdir(__home_path) is False:
            raise RuntimeError("Invalid path in command line option")

    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
コード例 #12
0
import os
import winreg

hkey = winreg.HKEY_CURRENT_USER
rkey = 'Software\Microsoft\Windows\CurrentVersion\Run'

rhandle = winreg.OpenKey(hkey, rkey, 0, winreg.KEY_ALL_ACCESS)
appdata = winreg.ExpandEnvironmentStrings('%appdata%')
bat = os.path.join(appdata, 'pyradio', 'help', 'pyradio.bat')
if ' ' in bat:
    bat = '"' + bat + '"'

try:
    winreg.SetValueEx(rhandle, 'PyRadioLockFile', 0, winreg.REG_SZ, bat)
    with open(bat, "w") as f:
        f.write('echo "Windows started" > "{}"\n'.format(
            os.path.join(appdata, 'pyradio', '_windows.lock')))
finally:
    winreg.CloseKey(rhandle)
コード例 #13
0
    def getKindleInfoFiles():
        kInfoFiles = []
        # 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
        path = ""
        if 'LOCALAPPDATA' in os.environ.keys():
            # Python 2.x does not return unicode env. Use Python 3.x
            path = winreg.ExpandEnvironmentStrings("%LOCALAPPDATA%")
            # this is just another alternative.
            # path = getEnvironmentVariable('LOCALAPPDATA')
            if not os.path.isdir(path):
                path = ""
        else:
            # User Shell Folders show take precedent over Shell Folders if present
            try:
                # this will still break
                regkey = winreg.OpenKey(
                    winreg.HKEY_CURRENT_USER,
                    "Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\User Shell Folders\\"
                )
                path = winreg.QueryValueEx(regkey, 'Local AppData')[0]
                if not os.path.isdir(path):
                    path = ""
                    try:
                        regkey = winreg.OpenKey(
                            winreg.HKEY_CURRENT_USER,
                            "Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders\\"
                        )
                        path = winreg.QueryValueEx(regkey, 'Local AppData')[0]
                        if not os.path.isdir(path):
                            path = ""
                    except RegError:
                        pass
            except RegError:
                pass

        found = False
        if path == "":
            print('Could not find the folder in which to look for kinfoFiles.')
        else:
            # Probably not the best. To Fix (shouldn't ignore in encoding) or use utf-8
            print("searching for kinfoFiles in " + path)

            # look for (K4PC 1.25.1 and later) .kinf2018 file
            kinfopath = path + '\\Amazon\\Kindle\\storage\\.kinf2018'
            if os.path.isfile(kinfopath):
                found = True
                print('Found K4PC 1.25+ kinf2018 file: ' + kinfopath)
                kInfoFiles.append(kinfopath)

            # look for (K4PC 1.9.0 and later) .kinf2011 file
            kinfopath = path + '\\Amazon\\Kindle\\storage\\.kinf2011'
            if os.path.isfile(kinfopath):
                found = True
                print('Found K4PC 1.9+ kinf2011 file: ' + kinfopath)
                kInfoFiles.append(kinfopath)

            # look for (K4PC 1.6.0 and later) rainier.2.1.1.kinf file
            kinfopath = path + '\\Amazon\\Kindle\\storage\\rainier.2.1.1.kinf'
            if os.path.isfile(kinfopath):
                found = True
                print('Found K4PC 1.6-1.8 kinf file: ' + kinfopath)
                kInfoFiles.append(kinfopath)

            # look for (K4PC 1.5.0 and later) rainier.2.1.1.kinf file
            kinfopath = path + '\\Amazon\\Kindle For PC\\storage\\rainier.2.1.1.kinf'
            if os.path.isfile(kinfopath):
                found = True
                print('Found K4PC 1.5 kinf file: ' + kinfopath)
                kInfoFiles.append(kinfopath)

        # look for original (earlier than K4PC 1.5.0) kindle-info files
            kinfopath = path + '\\Amazon\\Kindle For PC\\{AMAwzsaPaaZAzmZzZQzgZCAkZ3AjA_AY}\\kindle.info'
            if os.path.isfile(kinfopath):
                found = True
                print('Found K4PC kindle.info file: ' + kinfopath)
                kInfoFiles.append(kinfopath)

        if not found:
            print('No K4PC kindle.info/kinf/kinf2011 files have been found.')
        return kInfoFiles
コード例 #14
0
def sz_expand(value, value_type):
    if value_type == reg.REG_EXPAND_SZ:
        return reg.ExpandEnvironmentStrings(value)
    else:
        return value
コード例 #15
0
    def __init__ (self, serials = [], device_path = None, desktopkobodir = u""):
        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, ".kobo")
            # devices use KoboReader.sqlite
            kobodb  = os.path.join(self.kobodir, "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 "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 "trying to load {0}".format(devicexml)
                    if (os.path.exists(devicexml)):
                        # print "trying to parse {0}".format(devicexml)
                        xmltree = ET.parse(devicexml)
                        for node in xmltree.iter():
                            if "deviceSerial" in node.tag:
                                serial = node.text
                                # print "found serial {0}".format(serial)
                                serials.append(serial)
                                break
                    else:
                        # print "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 desktopkobodir != u'':
                self.kobodir = desktopkobodir

            if (self.kobodir == u""):
                if sys.platform.startswith('win'):
                    import 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("%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("%USERPROFILE%"), "Local Settings", "Application Data")
                    self.kobodir = os.path.join(self.kobodir, "Kobo", "Kobo Desktop Edition")
                elif sys.platform.startswith('darwin'):
                    self.kobodir = os.path.join(os.environ['HOME'], "Library", "Application Support", "Kobo", "Kobo Desktop Edition")
                elif sys.platform.startswith('linux'):

                    #sets ~/.config/calibre as the location to store the kobodir location info file and creates this directory if necessary
                    kobodir_cache_dir = os.path.join(os.environ['HOME'], ".config", "calibre")
                    if not os.path.isdir(kobodir_cache_dir):
                        os.mkdir(kobodir_cache_dir)
                    
                    #appends the name of the file we're storing the kobodir location info to the above path
                    kobodir_cache_file = str(kobodir_cache_dir) + "/" + "kobo location"
                    
                    """if the above file does not exist, recursively searches from the root
                    of the filesystem until kobodir is found and stores the location of kobodir
                    in that file so this loop can be skipped in the future"""
                    original_stdout = sys.stdout
                    if not os.path.isfile(kobodir_cache_file):
                        for root, dirs, files in os.walk('/'):
                            for file in files:
                                if file == 'Kobo.sqlite':
                                    kobo_linux_path = str(root)
                                    with open(kobodir_cache_file, 'w') as f:
                                        sys.stdout = f
                                        print(kobo_linux_path, end='')
                                        sys.stdout = original_stdout

                    f = open(kobodir_cache_file, 'r' )
                    self.kobodir = f.read()

            # desktop versions use Kobo.sqlite
            kobodb = os.path.join(self.kobodir, "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, "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(b'\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
コード例 #16
0
ファイル: wariety_config.py プロジェクト: gitRigge/Wariety
 def before_get(self, parser, section, option, value, defaults):
     return winreg.ExpandEnvironmentStrings(value.replace("'", ""))
コード例 #17
0
def getNookLogFiles():
    logFiles = []
    found = False
    if iswindows:
        try:
            import winreg
        except ImportError:
            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("%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(
                "%USERPROFILE%") + "\\AppData\\Local"
            if os.path.isdir(path):
                paths.add(path)
            path = winreg.ExpandEnvironmentStrings(
                "%USERPROFILE%") + "\\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, file=sys.stderr)
                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, file=sys.stderr)
            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, file=sys.stderr)
            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, file=sys.stderr)
            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, file=sys.stderr)
            found = True

    if not found:
        print('No nook Study log files have been found.', file=sys.stderr)
    return logFiles
コード例 #18
0
def expand(dong):
    """Expands environment variable placeholders, such as `%appdata%`"""

    return winreg.ExpandEnvironmentStrings(dong)
コード例 #19
0
ファイル: utils.py プロジェクト: vesnikos/wpTiller
    def gdal_root(path=None):
        """

        :param path:
        :return:
        """

        # is gdal installed in an exotic location? if yes overwrite the automatic
        if path:
            path = Path(path)
            return path

        os_name = platform.system()
        paths = []
        res = None
        if os_name == 'Windows':
            # Get from the registry the system paths.
            # Known location of registry based path locations
            sys_path = r'SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment'
            user_path = r'Environment'

            if sys.version_info.major == 3:
                import winreg
            else:  # sys.version_info.major == 2:
                import _winreg as winreg

            # user Path
            key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, user_path, 0,
                                 winreg.KEY_READ)
            query = winreg.QueryValueEx(key, 'Path')[0]
            for _ in query.split(';'):
                p = winreg.ExpandEnvironmentStrings(_)
                p = Path(p)
                paths.append(p)

            key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, sys_path, 0,
                                 winreg.KEY_READ)
            query = winreg.QueryValueEx(key, 'Path')[0]
            for _ in query.split(';'):
                p = winreg.ExpandEnvironmentStrings(_)
                p = Path(p)
                paths.append(p)
        elif os_name == 'Linux':
            env = os.environ['PATH'].split(':')
            for _ in env:
                _ = Path(_)
                paths.append(_)

        # Parse the evniroments for potential gdal roots
        for p in paths:
            # I assume where ever gdalinfo is, the rest of binaries are.
            q = list(p.glob('gdalinfo*'))
            if len(q) > 0:
                if len(q) > 1:
                    raise Exception('too many gdalinfos in %s ' % q)
                res = p
                break
        if res is None:
            raise Exception(
                'gdal root folder not found. Have you installed gdal?')

        res = res.as_posix()
        return res
コード例 #20
0
ファイル: obok.py プロジェクト: tracyde/DeDRM_tools
    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, ".kobo")
            # devices use KoboReader.sqlite
            kobodb = os.path.join(self.kobodir, "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 "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 "trying to load {0}".format(devicexml)
                    if (os.path.exists(devicexml)):
                        # print "trying to parse {0}".format(devicexml)
                        xmltree = ET.parse(devicexml)
                        for node in xmltree.iter():
                            if "deviceSerial" in node.tag:
                                serial = node.text
                                # print "found serial {0}".format(serial)
                                serials.append(serial)
                                break
                    else:
                        # print "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'):
                try:
                    import winreg
                except ImportError:
                    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(
                            "%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("%USERPROFILE%"),
                            "Local Settings", "Application Data")
                self.kobodir = os.path.join(self.kobodir, "Kobo",
                                            "Kobo Desktop Edition")
            elif sys.platform.startswith('darwin'):
                self.kobodir = os.path.join(os.environ['HOME'], "Library",
                                            "Application Support", "Kobo",
                                            "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, "Local Settings", "Application Data", "Kobo", "Kobo Desktop Edition")
            # desktop versions use Kobo.sqlite
            kobodb = os.path.join(self.kobodir, "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, "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
コード例 #21
0
def process_sources(outfile):
    files = set()
    with jsonstreams.Stream(jsonstreams.Type.OBJECT,
                            filename=outfile,
                            pretty=True,
                            indent=2) as sources_stream:
        with ConnectRegistry(None, HKEY_LOCAL_MACHINE) as hive:
            with OpenKey(hive, r"SYSTEM\CurrentControlSet\Services\EventLog",
                         0, KEY_READ) as event_log_key:
                for log in subkeys(event_log_key):
                    with sources_stream.subobject(log) as log_stream:
                        with OpenKey(event_log_key, log) as log_key:
                            for source in subkeys(log_key):
                                with log_stream.subobject(
                                        source) as source_stream:
                                    with OpenKey(log_key,
                                                 source) as source_key:
                                        event_message_file = value(
                                            source_key, "EventMessageFile")
                                        category_message_file = value(
                                            source_key, "CategoryMessageFile")
                                        category_count = value(
                                            source_key, "CategoryCount")
                                        parameter_message_file = value(
                                            source_key, "ParameterMessageFile")

                                        if category_count:
                                            source_stream.write(
                                                'category_count',
                                                category_count)

                                        if event_message_file:
                                            with source_stream.subarray(
                                                    'event_messages'
                                            ) as event_messages_stream:
                                                for zz in event_message_file.split(
                                                        ';'):
                                                    zz = winreg.ExpandEnvironmentStrings(
                                                        zz)
                                                    event_messages_stream.write(
                                                        zz)
                                                    files.add(zz)

                                        if category_message_file:
                                            with source_stream.subarray(
                                                    'category_messages'
                                            ) as category_messages_stream:
                                                for zz in category_message_file.split(
                                                        ';'):
                                                    zz = winreg.ExpandEnvironmentStrings(
                                                        zz)
                                                    category_messages_stream.write(
                                                        zz)
                                                    files.add(zz)

                                        if parameter_message_file:
                                            with source_stream.subarray(
                                                    'parameter_messages'
                                            ) as parameter_messages_stream:
                                                for zz in parameter_message_file.split(
                                                        ';'):
                                                    zz = winreg.ExpandEnvironmentStrings(
                                                        zz)
                                                    parameter_messages_stream.write(
                                                        zz)
                                                    files.add(zz)
    return files
コード例 #22
0
ファイル: unreg.py プロジェクト: codedarkness/pyradio
import os
import winreg

hkey = winreg.HKEY_CURRENT_USER
rkey = 'Software\Microsoft\Windows\CurrentVersion\Run'

rhandle = winreg.OpenKey(hkey, rkey, 0, winreg.KEY_ALL_ACCESS)

bat = os.path.join(winreg.ExpandEnvironmentStrings('%appdata%'), 'pyradio',
                   'help', 'pyradio.bat')
if ' ' in bat:
    bat = '"' + bat + '"'

try:
    winreg.DeleteValue(rhandle, 'PyRadioLockFile')
except:
    pass
finally:
    winreg.CloseKey(rhandle)