Exemplo n.º 1
0
def _find_devenv_path(vs_version):
    devenv_path = None

    # First try the registry, because the environment variable is unreliable
    # (case of Visual Studio installed on a different drive; it still sets
    # the envvar to point to C:\Program Files even if devenv.com is on D:\)
    #pylint: disable=import-error
    from winreg import OpenKey, QueryValue, HKEY_LOCAL_MACHINE
    key_path = 'SOFTWARE\\Classes\\VisualStudio.accessor.' + vs_version + '.0\\shell\\Open'
    try:
        with OpenKey(HKEY_LOCAL_MACHINE, key_path) as key:
            cmdline = QueryValue(key, 'Command')
            if cmdline[:1] == '"':
                cmdline = cmdline.split('"')[1]
            elif ' ' in cmdline:
                cmdline = cmdline.split(' ')[0]
            devenv_path = cmdline.replace('devenv.exe', 'devenv.com')
    #pylint: disable=broad-except
    except Exception:
        pass

    # If the registry key is unhelpful, try the environment variable
    if not devenv_path:
        vstools_path = os.getenv('VS' + vs_version + '0COMNTOOLS')
        if vstools_path is not None:
            # Sanitize this because os.path.join sometimes gets confused
            if vstools_path[-1] in [ '/', '\\' ]:
                vstools_path = vstools_path[:-1]
            devenv_path = os.path.join(vstools_path, '../../Common7/IDE/devenv.com')

    if not devenv_path or not os.path.exists(devenv_path):
        return None

    logging.info("Found Visual Studio at %s", devenv_path)
    return devenv_path
Exemplo n.º 2
0
def _find_devenv_path(vs_version):
    devenv_path = None

    # Sanitize vs_version
    if vs_version == '2015':
        vs_version = '14'
    if vs_version == '2017':
        vs_version = '15'
    if vs_version == '2019':
        vs_version = '16'

    # First try the registry, because the environment variable is unreliable
    # (case of Visual Studio installed on a different drive; it still sets
    # the envvar to point to C:\Program Files even if devenv.com is on D:\)
    #pylint: disable=import-error
    from winreg import OpenKey, QueryValue, HKEY_LOCAL_MACHINE
    key_path = 'SOFTWARE\\Classes\\VisualStudio.accessor.' + vs_version + '.0\\shell\\Open'
    try:
        with OpenKey(HKEY_LOCAL_MACHINE, key_path) as key:
            cmdline = QueryValue(key, 'Command')
            if cmdline[:1] == '"':
                cmdline = cmdline.split('"')[1]
            elif ' ' in cmdline:
                cmdline = cmdline.split(' ')[0]
            devenv_path = cmdline.replace('devenv.exe', 'devenv.com')
    #pylint: disable=broad-except
    except Exception:
        pass

    # For VS2017 and later, there is vswhere
    if not devenv_path:
        vswhere_path = os.path.join(os.environ['ProgramFiles(x86)'], 'Microsoft Visual Studio/Installer/vswhere.exe')
        result, output, _ = nimp.sys.process.call([vswhere_path], capture_output=True, hide_output=True)
        if result == 0:
            for line in output.split('\n'):
                line = line.strip()
                if 'installationPath: ' in line:
                    candidate = line.split(' ', 1)[1]
                elif 'installationVersion: ' + vs_version in line:
                    devenv_path = os.path.join(candidate, 'Common7/IDE/devenv.com')
                    break

    # If the registry key is unhelpful, try the environment variable
    if not devenv_path:
        vstools_path = os.getenv('VS' + vs_version + '0COMNTOOLS')
        if vstools_path is not None:
            # Sanitize this because os.path.join sometimes gets confused
            if vstools_path[-1] in [ '/', '\\' ]:
                vstools_path = vstools_path[:-1]
            devenv_path = os.path.join(vstools_path, '../../Common7/IDE/devenv.com')

    if not devenv_path or not os.path.exists(devenv_path):
        return None

    devenv_path = os.path.normpath(devenv_path)
    logging.info("Found Visual Studio at %s", devenv_path)
    return devenv_path
Exemplo n.º 3
0
def get_browser():
    cmd = str()
    with OpenKey(HKEY_CURRENT_USER,
                 r"Software\Classes\http\shell\open\command") as key:
        cmd = QueryValue(key, None)
    if cmd.lower().__contains__('firefox'):
        return 'firefox'
    elif cmd.lower().__contains__('chrome'):
        return 'chrome'
    else:
        return 'other'
Exemplo n.º 4
0
def verify_registry():
    regHandle = ConnectRegistry(None, HKEY_LOCAL_MACHINE)
    keyHandle = OpenKey(regHandle, r"SOFTWARE\Mozilla\NativeMessagingHosts\org.cryptable.pki.keymgmnt", access=KEY_READ)
    data = QueryValue(keyHandle, None)
    print(data)
    if data != r"C:\Program Files\Cryptable\Key Management Web Extension\org.cryptable.pki.keymgmnt.json":
        raise "registry verification error"
Exemplo n.º 5
0
    def get_python_install_path(self, major, minor):
        """ Return the name of the directory containing the root of a Python
        installation directory.  It must not be called on a non-Windows
        platform.
        """

        from winreg import HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE, QueryValue

        reg_version = '{}.{}'.format(major, minor)
        if self.target_arch_name.endswith('-32'):
            reg_version += '-32'

        sub_key_user = '******'.format(
            reg_version)
        sub_key_all_users = 'Software\\Wow6432Node\\Python\\PythonCore\\{}\\InstallPath'.format(
            reg_version)

        queries = ((HKEY_CURRENT_USER, sub_key_user),
                   (HKEY_LOCAL_MACHINE, sub_key_user), (HKEY_LOCAL_MACHINE,
                                                        sub_key_all_users))

        for key, sub_key in queries:
            try:
                install_path = QueryValue(key, sub_key)
            except OSError:
                pass
            else:
                break
        else:
            self.error("unable to find an installation of Python v{0}".format(
                reg_version))

        return install_path
Exemplo n.º 6
0
def write_mobi(options: WriterOptions):
    try:
        kindlegen = find_tool('kindlegen')

        if kindlegen is None and os.name == 'nt':
            kindlegen = Path(
                QueryValue(HKEY_CURRENT_USER,
                           r'Software\Amazon\Kindle Previewer 3')).joinpath(
                               'lib/fc/bin/kindlegen.exe').resolve()
    except FileNotFoundError as e:
        raise Exception(
            'Could not find KindleGen. Please install Kindle Previewer 3.'
        ) from e

    with TemporaryDirectory() as work_dir:
        work_dir = Path(work_dir)
        epub = work_dir.joinpath('temp.epub')
        write_epub(dataclasses.replace(options, output_path=str(epub)))

        # Necessary because KindleGen will only put the output mobi into
        # the same directory as the source epub. I wish I was kidding.
        temp_mobi_path = work_dir.joinpath('temp.mobi')

        process = subprocess.run(
            [kindlegen, epub, '-o',
             str(temp_mobi_path.name)])

        # return code of 1 means warnings, but book was built
        if process.returncode not in [0, 1]:
            raise Exception(
                f'KindleGen died with exit code {process.returncode}.\n' +
                'Also tell jcotton42 to get off his butt and do error handling right.'
            )

        temp_mobi_path.replace(options.output_path)
Exemplo n.º 7
0
 def _find_exe_in_registry(self):
     try:
         from winreg import OpenKey, QueryValue, HKEY_LOCAL_MACHINE
     except ImportError:
         from winreg import OpenKey, QueryValue, HKEY_LOCAL_MACHINE
     import shlex
     keys = (
         r"SOFTWARE\Classes\FirefoxHTML\shell\open\command",
         r"SOFTWARE\Classes\Applications\firefox.exe\shell\open\command"
     )
     command = ""
     for path in keys:
         try:
             key = OpenKey(HKEY_LOCAL_MACHINE, path)
             command = QueryValue(key, "")
             break
         except OSError:
             pass
     else:
         return ""
     
     if not command:
         return ""
     
     return shlex.split(command)[0]
Exemplo n.º 8
0
def maybe_set_key(key_path: str, expected: str, dry_run: bool = False, var_name: str = None):
    from winreg import HKEY_CLASSES_ROOT, OpenKey, QueryValue, CreateKeyEx, SetValue, REG_SZ, KEY_WRITE, KEY_READ
    from winreg import QueryValueEx, SetValueEx
    try:
        with OpenKey(HKEY_CLASSES_ROOT, key_path, 0, KEY_READ) as entry_key:
            if var_name:
                value = QueryValueEx(entry_key, var_name)[0]
            else:
                value = QueryValue(entry_key, None)
    except FileNotFoundError:
        value = None

    if value != expected:
        prefix = '[DRY RUN] Would set' if dry_run else 'Setting'
        if var_name:
            log.info(f'{prefix} HKEY_CLASSES_ROOT\\{key_path}[{var_name!r}] = {expected!r}')
        else:
            log.info(f'{prefix} HKEY_CLASSES_ROOT\\{key_path} = {expected!r}')

        if not dry_run:
            with CreateKeyEx(HKEY_CLASSES_ROOT, key_path, 0, KEY_WRITE) as entry_key:
                if var_name:
                    SetValueEx(entry_key, var_name, 0, REG_SZ, expected)
                else:
                    SetValue(entry_key, None, REG_SZ, expected)  # noqa
    else:
        log.info(f'Already contains expected value: HKEY_CLASSES_ROOT\\{key_path}')
Exemplo n.º 9
0
 def convert_report(self, report, ext):
     converted = False
     with self.task.lock('$report_conversion'):
         try:
             from subprocess import Popen, STDOUT, PIPE
             if os.name == "nt":
                 regpath = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths\\soffice.exe"
                 root = OpenKey(HKEY_LOCAL_MACHINE, regpath)
                 s_office = QueryValue(root, "")
             else:
                 s_office = "soffice"
             convertion = Popen([s_office, '--headless', '--convert-to', ext,
                 report.report_filename, '--outdir', os.path.join(self.work_dir, 'static', 'reports')],
                 stderr=STDOUT,stdout=PIPE)
             out, err = convertion.communicate()
             converted = True
         except Exception as e:
             self.log.exception(error_message(e))
     return converted
Exemplo n.º 10
0
def get_py_install_path(version, target):
    """ Return the name of the directory containing the root of the Python
    installation directory for a particular version and target.  It must not be
    called on a non-Windows platform.
    """

    from winreg import HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE, QueryValue

    major, minor, _ = version
    reg_version = '{0}.{1}'.format(major, minor)
    if (major, minor) >= (3, 5) and target.name.endswith('-32'):
        reg_version += '-32'

    sub_key_user = '******'.format(
            reg_version)
    sub_key_all_users = 'Software\\Wow6432Node\\Python\\PythonCore\\{}\\InstallPath'.format(
            reg_version)

    queries = (
        (HKEY_CURRENT_USER, sub_key_user),
        (HKEY_LOCAL_MACHINE, sub_key_user),
        (HKEY_LOCAL_MACHINE, sub_key_all_users))

    for key, sub_key in queries:
        try:
            install_path = QueryValue(key, sub_key)
        except OSError:
            pass
        else:
            break
    else:
        raise UserException(
                "Unable to find an installation of Python v{0}.".format(
                        reg_version))

    return install_path
Exemplo n.º 11
0
def build_host_python(host, target_name, optional, use_system_python):
    """ Build (or install) a host Python. """

    if use_system_python is None:
        if sys.platform == 'win32':
            fatal(
                "Building the host Python from source on Windows is not supported"
            )

        source = host.sysroot.find_source('Python-*', optional=optional)
        if source is None:
            return

        host.sysroot.unpack_source(source)

        py_version = source.split('-')[1].split('.')

        # ensurepip was added in Python v2.7.9 and v3.4.0.
        ensure_pip = False
        if py_version[0] == '2':
            if py_version[2] >= '9':
                ensure_pip = True
        elif py_version[1] >= '4':
            ensure_pip = True

        configure = ['./configure', '--prefix', host.sysroot.host_python_dir]
        if ensure_pip:
            configure.append('--with-ensurepip=no')

        host.run(*configure)
        host.run(host.make)
        host.run(host.make, 'install')

        interp = os.path.join(host.sysroot.host_python_dir, 'bin',
                              'python' + '.'.join(py_version[:2]))
    elif sys.platform == 'win32':
        from winreg import (HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE, QueryValue)

        py_major, py_minor = use_system_python.split('.')
        reg_version = use_system_python
        if int(py_major) == 3 and int(
                py_minor
        ) >= 5 and target_name is not None and target_name.endswith('-32'):
            reg_version += '-32'

        sub_key_user = '******'.format(
            reg_version)
        sub_key_all_users = 'Software\\Wow6432Node\\Python\\PythonCore\\{}\\InstallPath'.format(
            reg_version)

        queries = ((HKEY_CURRENT_USER, sub_key_user),
                   (HKEY_LOCAL_MACHINE, sub_key_user), (HKEY_LOCAL_MACHINE,
                                                        sub_key_all_users))

        for key, sub_key in queries:
            try:
                install_path = QueryValue(key, sub_key)
            except OSError:
                pass
            else:
                break
        else:
            fatal("Unable to find an installation of Python v{}".format(
                reg_version))

        interp = install_path + 'python.exe'

        # Copy the DLL.  The .exe will get copied later.
        dll = 'python' + py_major + py_minor + '.dll'
        make_directory(host.sysroot.bin_dir)
        shutil.copyfile(os.path.join(install_path, dll),
                        os.path.join(host.sysroot.bin_dir, dll))
    else:
        interp = 'python' + use_system_python

    host.python.get_configuration(interp)

    # Create symbolic links to the interpreter in a standard place in sysroot
    # so that they can be referred to in cross-target .pdy files.
    make_symlink(str(host.sysroot), host.python.interpreter, host.interpreter)
Exemplo n.º 12
0
    def getMODirectory(gameName):
        #This custom function is used to detect the location of Mod Organizer

        ModOrganizerINILocationFromConfig = ModifyINI("Bethini.ini").get_value("Directories", "s" + gameName + "ModOrganizerINIPath", default="Not Detected")

        pathValue = "Not Detected"
        gameReg = Info.nxmhandler_game_reference(gameName)

        #Look up the nxm link (download with mod manager links on the
        #NexusMods.com sites) handler to find Mod Organizer location
        try:
            nxm = QueryValue(OpenKey(ConnectRegistry(None, HKEY_CLASSES_ROOT), r'nxm\shell\open\command'),"")
            sm(f'NXM links point to {nxm}')
            if 'nxmhandler' in nxm:
                nxmhandler = nxm.split('\"')[1]
                nxmhandlers = nxmhandler.replace("nxmhandler.exe","nxmhandlers.ini")
                if os.path.isfile(nxmhandlers):
                    nxmhandlersINI = ModifyINI(nxmhandlers)
                    sm(f'nxmhandlers.ini found here: {nxmhandlers}')
        except:
            sm('NXM links are probably not set up.', exception=1)
        
        try:
            nxmhandlersINI
        except:
            #nxmhandlers.ini not found.  Check for the AppData location.
            sm('nxmhandlers.ini not found. Checking AppData location.', exception=1)
            AppDataLocation = str(pathlib.Path.home()) + r"\AppData\Local\ModOrganizer\nxmhandler.ini"
            if os.path.isfile(AppDataLocation):
                nxmhandlers = AppDataLocation
                nxmhandlersINI = ModifyINI(nxmhandlers)
                sm(f'nxmhandler.ini found in {nxmhandlers}')
        try:
            size = int(nxmhandlersINI.get_value('handlers', 'size')) + 1
            for n in range(size):
                key = str(n) + '\\games'
                value = nxmhandlersINI.get_value('handlers', key)
                if gameReg != "skyrimse":
                    value = value.replace('skyrimse','')
                if gameReg in value:
                    pathKey = str(n) + '\\executable'
                    pathValue = os.path.split(nxmhandlersINI.get_value('handlers', pathKey).replace('\\\\','\\'))[0]
                    pathValue += '\\'
                    sm(f'Mod Organizer appears to be located at {pathValue}')
        except:
            sm('There is probably no nxmhandler.ini.', exception=1)

        ModOrganizerINILocation = 'Not Detected'
        if os.path.isfile(f'{pathValue}ModOrganizer.ini'):
            ModOrganizerINILocation = f'{pathValue}ModOrganizer.ini'
            sm(f'Found {ModOrganizerINILocation}')
        elif os.path.isfile(str(pathlib.Path.home()) + f"\\AppData\\Local\\ModOrganizer\\{gameReg}\\ModOrganizer.ini"):
            ModOrganizerINILocation = str(pathlib.Path.home()) + f"\\AppData\\Local\\ModOrganizer\\{gameReg}\\ModOrganizer.ini"
            sm(f'Found {ModOrganizerINILocation}')
        if ModOrganizerINILocation != 'Not Detected':
            ModOrganizerINILocation = os.path.split(ModOrganizerINILocation)[0]
            ModOrganizerINILocation += '\\'
        else:
            sm('Failed to locate ModOrganizer.ini')
            ModOrganizerINILocation = ModOrganizerINILocationFromConfig
            
        if ModOrganizerINILocation != ModOrganizerINILocationFromConfig and ModOrganizerINILocationFromConfig != "Not Detected":
            return [ModOrganizerINILocationFromConfig,ModOrganizerINILocation,"Browse..."]

        return [ModOrganizerINILocation,"Browse...","Manual..."]
Exemplo n.º 13
0
 def test_simple_write(self):
     from winreg import SetValue, QueryValue, REG_SZ
     value = "Some Default value"
     SetValue(self.root_key, self.test_key_name, REG_SZ, value)
     assert QueryValue(self.root_key, self.test_key_name) == value
Exemplo n.º 14
0
def qadShowPluginHelp(section="", filename="index", packageName=None):
    """
   show a help in the user's html browser.
   per conoscere la sezione/pagina del file html usare internet explorer,
   selezionare nella finestra di destra la voce di interesse e leggerne l'indirizzo dalla casella in alto.
   Questo perché internet explorer inserisce tutti i caratteri di spaziatura e tab che gli altri browser non fanno.
   """
    try:
        basepath = ""
        if packageName is None:
            basepath = os.path.dirname(os.path.realpath(__file__))
        else:
            basepath = os.path.dirname(
                os.path.realpath(sys.modules[packageName].__file__))
    except:
        return

    # initialize locale
    userLocaleList = QSettings().value("locale/userLocale").split("_")
    language = userLocaleList[0]
    region = userLocaleList[1] if len(userLocaleList) > 1 else ""

    path = QDir.cleanPath(basepath + "/help/help")
    helpPath = path + "_" + language + "_" + region  # provo a caricare la lingua e la regione selezionate

    if not os.path.exists(helpPath):
        helpPath = path + "_" + language  # provo a caricare la lingua
        if not os.path.exists(helpPath):
            helpPath = path + "_en"  # provo a caricare la lingua inglese
            if not os.path.exists(helpPath):
                return

    helpfile = os.path.join(helpPath, filename + ".html")
    if os.path.exists(helpfile):
        url = "file:///" + helpfile

        if section != "":
            url = url + "#" + urllib.parse.quote(section.encode('utf-8'))

        # la funzione QDesktopServices.openUrl in windows non apre la sezione
        if platform.system() == "Windows":
            import subprocess
            from winreg import HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE, OpenKey, QueryValue

            try:  # provo a livello di utente
                with OpenKey(
                        HKEY_CURRENT_USER,
                        r"Software\Classes\http\shell\open\command") as key:
                    cmd = QueryValue(key, None)
            except:  # se non c'era a livello di utente provo a livello di macchina
                with OpenKey(
                        HKEY_LOCAL_MACHINE,
                        r"Software\Classes\http\shell\open\command") as key:
                    cmd = QueryValue(key, None)

            if cmd.find("\"%1\"") >= 0:
                subprocess.Popen(cmd.replace("%1", url))
            else:
                if cmd.find("%1") >= 0:
                    subprocess.Popen(cmd.replace("%1", "\"" + url + "\""))
                else:
                    subprocess.Popen(cmd + " \"" + url + "\"")
        else:
            QDesktopServices.openUrl(QUrl(url))
Exemplo n.º 15
0
def getDefaultBrowser():
    with OpenKey(HKEY_CURRENT_USER,
                 r"Software\Classes\http\shell\open\command") as key:
        cmd = QueryValue(key, None)
    return cmd