def get_Chrome_version():
    key = winreg.OpenKey(winreg.HKEY_CURRENT_USER,
                         r'Software\Google\Chrome\BLBeacon')
    version, types = winreg.QueryValueEx(key, 'version')
    return version
def get_diagnostic_information():
    '''Get diagnostic information about the system state that is suitable for printing or logging

    returns: dict

    note: Python bitness may be incorrect when running in a virtual environment
    '''
    import os
    import pkg_resources
    import platform
    import struct
    import sys

    def is_python_64bit():
        return (struct.calcsize("P") == 8)

    def is_os_64bit():
        return platform.machine().endswith('64')

    def is_venv():
        return 'VIRTUAL_ENV' in os.environ

    info = {}
    info['os'] = {}
    info['python'] = {}
    info['driver'] = {}
    info['module'] = {}
    if platform.system() == 'Windows':
        try:
            import winreg as winreg
        except ImportError:
            import _winreg as winreg

        os_name = 'Windows'
        try:
            driver_version_key = winreg.OpenKey(
                winreg.HKEY_LOCAL_MACHINE,
                r"SOFTWARE\National Instruments\NI-ModInst\CurrentVersion")
            driver_version = winreg.QueryValueEx(driver_version_key,
                                                 "Version")[0]
        except WindowsError:
            driver_version = 'Unknown'
    elif platform.system() == 'Linux':
        os_name = 'Linux'
        driver_version = 'Unknown'
    else:
        raise SystemError('Unsupported platform: {}'.format(platform.system()))

    installed_packages = pkg_resources.working_set
    installed_packages_list = [{
        'name': i.key,
        'version': i.version,
    } for i in installed_packages]

    info['os']['name'] = os_name
    info['os']['version'] = platform.version()
    info['os']['bits'] = '64' if is_os_64bit() else '32'
    info['driver']['name'] = "NI-ModInst"
    info['driver']['version'] = driver_version
    info['module']['name'] = 'nimodinst'
    info['module']['version'] = "1.3.2.dev0"
    info['python']['version'] = sys.version
    info['python']['bits'] = '64' if is_python_64bit() else '32'
    info['python']['is_venv'] = is_venv()
    info['python']['packages'] = installed_packages_list

    return info
Exemple #3
0
        'C:\\Program Files\\7-Zip\\7z.exe',
        'C:\\Program Files (x86)\\7-Zip\\7z.exe',
    ]

    try:
        import winreg
    except ImportError:
        import _winreg as winreg  # For Python 2.

    try:
        hkey = winreg.OpenKey(winreg.HKEY_CURRENT_USER, 'Software\\7-Zip')
    except WindowsError:
        pass
    else:
        win_7z_path = os.path.join(
            winreg.QueryValueEx(hkey, 'Path')[0], '7z.exe')
        winreg.CloseKey(hkey)
        win_7z_exes.insert(1, win_7z_path)

    switch_7z = 'x -y'
    # Future suport:
    # 7-zip cannot extract tar.* with single command.
    #    ".tar.gz", ".tgz",
    #    ".tar.bz2", ".tbz",
    #    ".tar.lzma", ".tlz",
    #    ".tar.xz", ".txz",
    exts_7z = ['.rar', '.zip', '.tar', '.7z', '.xz', '.lzma']
    for win_7z_exe in win_7z_exes:
        if which(win_7z_exe):
            EXTRACT_COMMANDS = dict.fromkeys(exts_7z, [win_7z_exe, switch_7z])
            break
def _get_executable_info(name):
    """
    Get the version of some executable that Matplotlib optionally depends on.

    .. warning:
       The list of executables that this function supports is set according to
       Matplotlib's internal needs, and may change without notice.

    Parameters
    ----------
    name : str
        The executable to query.  The following values are currently supported:
        "dvipng", "gs", "inkscape", "magick", "pdftops".  This list is subject
        to change without notice.

    Returns
    -------
    If the executable is found, a namedtuple with fields ``executable`` (`str`)
    and ``version`` (`distutils.version.LooseVersion`, or ``None`` if the
    version cannot be determined).

    Raises
    ------
    ExecutableNotFoundError
        If the executable is not found or older than the oldest version
        supported by Matplotlib.
    ValueError
        If the executable is not one that we know how to query.
    """
    def impl(args, regex, min_ver=None, ignore_exit_code=False):
        # Execute the subprocess specified by args; capture stdout and stderr.
        # Search for a regex match in the output; if the match succeeds, the
        # first group of the match is the version.
        # Return an _ExecInfo if the executable exists, and has a version of
        # at least min_ver (if set); else, raise ExecutableNotFoundError.
        try:
            output = subprocess.check_output(args,
                                             stderr=subprocess.STDOUT,
                                             universal_newlines=True,
                                             errors="replace")
        except subprocess.CalledProcessError as _cpe:
            if ignore_exit_code:
                output = _cpe.output
            else:
                raise ExecutableNotFoundError(str(_cpe)) from _cpe
        except OSError as _ose:
            raise ExecutableNotFoundError(str(_ose)) from _ose
        match = re.search(regex, output)
        if match:
            version = LooseVersion(match.group(1))
            if min_ver is not None and version < min_ver:
                raise ExecutableNotFoundError(
                    f"You have {args[0]} version {version} but the minimum "
                    f"version supported by Matplotlib is {min_ver}")
            return _ExecInfo(args[0], version)
        else:
            raise ExecutableNotFoundError(
                f"Failed to determine the version of {args[0]} from "
                f"{' '.join(args)}, which output {output}")

    if name == "dvipng":
        return impl(["dvipng", "-version"], "(?m)^dvipng(?: .*)? (.+)", "1.6")
    elif name == "gs":
        execs = (["gswin32c", "gswin64c", "mgs", "gs"]  # "mgs" for miktex.
                 if sys.platform == "win32" else ["gs"])
        for e in execs:
            try:
                return impl([e, "--version"], "(.*)", "9")
            except ExecutableNotFoundError:
                pass
        message = "Failed to find a Ghostscript installation"
        raise ExecutableNotFoundError(message)
    elif name == "inkscape":
        info = impl(["inkscape", "-V"], "^Inkscape ([^ ]*)")
        if info and info.version >= "1.0":
            raise ExecutableNotFoundError(
                f"You have Inkscape version {info.version} but Matplotlib "
                f"only supports Inkscape<1.0")
        return info
    elif name == "magick":
        path = None
        if sys.platform == "win32":
            # Check the registry to avoid confusing ImageMagick's convert with
            # Windows's builtin convert.exe.
            import winreg
            binpath = ""
            for flag in [0, winreg.KEY_WOW64_32KEY, winreg.KEY_WOW64_64KEY]:
                try:
                    with winreg.OpenKeyEx(winreg.HKEY_LOCAL_MACHINE,
                                          r"Software\Imagemagick\Current", 0,
                                          winreg.KEY_QUERY_VALUE
                                          | flag) as hkey:
                        binpath = winreg.QueryValueEx(hkey, "BinPath")[0]
                except OSError:
                    pass
            if binpath:
                for name in ["convert.exe", "magick.exe"]:
                    candidate = Path(binpath, name)
                    if candidate.exists():
                        path = str(candidate)
                        break
        else:
            path = "convert"
        if path is None:
            raise ExecutableNotFoundError(
                "Failed to find an ImageMagick installation")
        return impl([path, "--version"], r"^Version: ImageMagick (\S*)")
    elif name == "pdftops":
        info = impl(["pdftops", "-v"],
                    "^pdftops version (.*)",
                    ignore_exit_code=True)
        if info and not ("3.0" <= info.version
                         # poppler version numbers.
                         or "0.9" <= info.version <= "1.0"):
            raise ExecutableNotFoundError(
                f"You have pdftops version {info.version} but the minimum "
                f"version supported by Matplotlib is 3.0")
        return info
    else:
        raise ValueError("Unknown executable: {!r}".format(name))
def get_steam_path() -> str:
    with winreg.OpenKey(winreg.HKEY_CURRENT_USER,
                        "Software\\Valve\\Steam") as key:
        return winreg.QueryValueEx(key, "SteamPath")[0]
Exemple #6
0
    def _generate() -> t.Optional[t.Union[str, bytes]]:
        linux = b""

        # machine-id is stable across boots, boot_id is not.
        for filename in "/etc/machine-id", "/proc/sys/kernel/random/boot_id":
            try:
                with open(filename, "rb") as f:
                    value = f.readline().strip()
            except OSError:
                continue

            if value:
                linux += value
                break

        # Containers share the same machine id, add some cgroup
        # information. This is used outside containers too but should be
        # relatively stable across boots.
        try:
            with open("/proc/self/cgroup", "rb") as f:
                linux += f.readline().strip().rpartition(b"/")[2]
        except OSError:
            pass

        if linux:
            return linux

        # On OS X, use ioreg to get the computer's serial number.
        try:
            # subprocess may not be available, e.g. Google App Engine
            # https://github.com/pallets/werkzeug/issues/925
            from subprocess import Popen, PIPE

            dump = Popen(["ioreg", "-c", "IOPlatformExpertDevice", "-d", "2"],
                         stdout=PIPE).communicate()[0]
            match = re.search(b'"serial-number" = <([^>]+)', dump)

            if match is not None:
                return match.group(1)
        except (OSError, ImportError):
            pass

        # On Windows, use winreg to get the machine guid.
        if sys.platform == "win32":
            import winreg

            try:
                with winreg.OpenKey(
                        winreg.HKEY_LOCAL_MACHINE,
                        "SOFTWARE\\Microsoft\\Cryptography",
                        0,
                        winreg.KEY_READ | winreg.KEY_WOW64_64KEY,
                ) as rk:
                    guid: t.Union[str, bytes]
                    guid_type: int
                    guid, guid_type = winreg.QueryValueEx(rk, "MachineGuid")

                    if guid_type == winreg.REG_SZ:
                        return guid.encode("utf-8")

                    return guid
            except OSError:
                pass

        return None
Exemple #7
0
def _read_sys_env(environement_variable_name):
    key = winreg.CreateKey(
        winreg.HKEY_LOCAL_MACHINE,
        r"System\CurrentControlSet\Control\Session Manager\Environment",
    )
    return winreg.QueryValueEx(key, environement_variable_name)[0]
Exemple #8
0
def find_lib():
    dll = None
    plugin_path = os.environ.get('PYTHON_VLC_MODULE_PATH', None)
    if 'PYTHON_VLC_LIB_PATH' in os.environ:
        try:
            dll = ctypes.CDLL(os.environ['PYTHON_VLC_LIB_PATH'])
        except OSError:
            logger.error(
                "Cannot load lib specified by PYTHON_VLC_LIB_PATH env. variable"
            )
            sys.exit(1)
    if plugin_path and not os.path.isdir(plugin_path):
        logger.error("Invalid PYTHON_VLC_MODULE_PATH specified. Please fix.")
        sys.exit(1)
    if dll is not None:
        return dll, plugin_path

    if sys.platform.startswith('win'):
        libname = 'libvlc.dll'
        p = find_library(libname)
        if p is None:
            try:  # some registry settings
                # leaner than win32api, win32con
                if PYTHON3:
                    import winreg as w
                else:
                    import _winreg as w
                for r in w.HKEY_LOCAL_MACHINE, w.HKEY_CURRENT_USER:
                    try:
                        r = w.OpenKey(r, 'Software\\VideoLAN\\VLC')
                        plugin_path, _ = w.QueryValueEx(r, 'InstallDir')
                        w.CloseKey(r)
                        break
                    except w.error:
                        pass
            except ImportError:  # no PyWin32
                pass
            if plugin_path is None:
                # try some standard locations.
                programfiles = os.environ["ProgramFiles"]
                homedir = os.environ["HOMEDRIVE"]
                for p in ('{programfiles}\\VideoLan{libname}',
                          'hotexamples_com:\\VideoLan{libname}',
                          '{programfiles}{libname}', 'hotexamples_com:{libname}'):
                    p = p.format(homedir=homedir,
                                 programfiles=programfiles,
                                 libname='\\VLC\\' + libname)
                    if os.path.exists(p):
                        plugin_path = os.path.dirname(p)
                        break
            if plugin_path is not None:  # try loading
                # PyInstaller Windows fix
                if 'PyInstallerCDLL' in ctypes.CDLL.__name__:
                    ctypes.windll.kernel32.SetDllDirectoryW(None)
                p = os.getcwd()
                os.chdir(plugin_path)
                # if chdir failed, this will raise an exception
                dll = ctypes.CDLL('.\\' + libname)
                # restore cwd after dll has been loaded
                os.chdir(p)
            else:  # may fail
                dll = ctypes.CDLL('.\\' + libname)
        else:
            plugin_path = os.path.dirname(p)
            dll = ctypes.CDLL(p)

    elif sys.platform.startswith('darwin'):
        # FIXME: should find a means to configure path
        d = '/Applications/VLC.app/Contents/MacOS/'
        c = d + 'lib/libvlccore.dylib'
        p = d + 'lib/libvlc.dylib'
        if os.path.exists(p) and os.path.exists(c):
            # pre-load libvlccore VLC 2.2.8+
            ctypes.CDLL(c)
            dll = ctypes.CDLL(p)
            for p in ('modules', 'plugins'):
                p = d + p
                if os.path.isdir(p):
                    plugin_path = p
                    break
        else:  # hope, some [DY]LD_LIBRARY_PATH is set...
            # pre-load libvlccore VLC 2.2.8+
            ctypes.CDLL('libvlccore.dylib')
            dll = ctypes.CDLL('libvlc.dylib')

    else:
        # All other OSes (linux, freebsd...)
        p = find_library('vlc')
        try:
            dll = ctypes.CDLL(p)
        except OSError:  # may fail
            dll = None
        if dll is None:
            try:
                dll = ctypes.CDLL('libvlc.so.5')
            except:
                raise NotImplementedError('Cannot find libvlc lib')

    return (dll, plugin_path)
Exemple #9
0
def iter_mfc(plat_name: str) -> Iterator[str]:
    if sys.hexversion < 0x2060000:
        # hrm - there doesn't seem to be a 'redist' directory for this
        # compiler (even the installation CDs only seem to have the MFC
        # DLLs in the 'win\system' directory - just grab it from
        # system32 (but we can't even use win32api for that!)
        src = os.path.join(
            os.environ.get('SystemRoot'), 'System32', 'mfc71.dll')
        if not os.path.isfile(src):
            raise RuntimeError('Can\'t find {}'.format(src))
        yield src
    else:
        plat_dir_64 = 'x64'
        # 2.6, 2.7, 3.0, 3.1 and 3.2 all use(d) vs2008 (compiler
        # version 1500)
        if sys.hexversion < 0x3030000:
            product_key = r'SOFTWARE\Microsoft\VisualStudio\9.0\Setup\VC'
            plat_dir_64 = 'amd64'
            mfc_dir = 'Microsoft.VC90.MFC'
            mfc_files = [
                'mfc90.dll',
                'mfc90u.dll',
                'mfcm90.dll',
                'mfcm90u.dll',
                'Microsoft.VC90.MFC.manifest',
            ]
        # 3.3 and 3.4 use(d) vs2010 (compiler version 1600, crt=10)
        elif sys.hexversion < 0x3050000:
            product_key = r'SOFTWARE\Microsoft\VisualStudio\10.0\Setup\VC'
            mfc_dir = 'Microsoft.VC100.MFC'
            mfc_files = ['mfc100u.dll', 'mfcm100u.dll']
        # 3.5 and later on vs2015 (compiler version 1900, crt=14)
        elif sys.hexversion < 0x3070000:
            product_key = r'SOFTWARE\Microsoft\VisualStudio\14.0\Setup\VC'
            mfc_dir = 'Microsoft.VC140.MFC'
            mfc_files = ['mfc140u.dll', 'mfcm140u.dll']
        else:
            product_key = ''
            mfc_dir = 'Microsoft.VC150.MFC'
            mfc_files = ['mfc140u.dll', 'mfcm140u.dll']

        # On a 64bit host, the value we are looking for is actually in
        # SysWow64Node - but that is only available on xp and later.
        access = winreg.KEY_READ
        if sys.getwindowsversion()[0] >= 5:
            access = access | 512  # KEY_WOW64_32KEY
        if plat_name == 'win-amd64':
            plat_dir = plat_dir_64
        else:
            plat_dir = 'x86'

        if product_key != '':
            # Find the redist directory.
            vckey = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, product_key, 0,
                                   access)
            val, val_typ = winreg.QueryValueEx(vckey, 'ProductDir')
        else:
            vckey = ''
            val = get_install_dir()

        mfc_dir = os.path.join(val, 'redist', plat_dir, mfc_dir)
        if not os.path.isdir(mfc_dir):
            raise RuntimeError(
                'Can\'t find the redist dir at {}'.format(mfc_dir))
        for f in mfc_files:
            yield os.path.join(mfc_dir, f)
Exemple #10
0

def GetProgramFiles64():
    if Is64Windows():
        return os.environ['PROGRAMW6432']
    else:
        return None


if Is64Windows() is True:
    key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE,
                         "SOFTWARE\\Wow6432Node\\Valve\\Steam")
else:
    key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, "SOFTWARE\\Valve\\Steam")

steampath = winreg.QueryValueEx(key, "InstallPath")[0]


@lru_cache(maxsize=32)
def GetSteamPath():
    return steampath


@lru_cache(maxsize=32)
def GetSteamLibraryPaths():
    with open(GetSteamPath() + "/SteamApps/LibraryFolders.vdf") as lf:
        vdffile = vdf.parse(lf)
        vdflocations = [
            val
            for key, val in vdffile['LibraryFolders'].items() if key.isdigit()
        ] + [steampath]
Exemple #11
0
        ver = Version(link)
        if latest < ver:
            latest = ver
    return latest


if __name__ == '__main__':
    reg = winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE)
    key = r"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\{8BEE1CDD-F95D-4759-952D-6B38DF99D1F0}"

    with winreg.OpenKey(reg,
                        key,
                        access=winreg.KEY_READ | winreg.KEY_WOW64_32KEY) as lo:
        try:
            lover = winreg.QueryValueEx(
                lo,
                "DisplayVersion")[0][:-2]  # Remove out last part of version
        except FileNotFoundError:
            lover = '0.0'

    installed_version = Version(lover)

    latest_version = get_latest_version(
        "http://download.documentfoundation.org/libreoffice/stable/")

    if installed_version < latest_version:
        print("A new version is available: {0}".format(latest_version))
    elif installed_version > latest_version:
        print("You have a higher version installed than available: {0} > {1}".
              format(installed_version, latest_version))
    else:
Exemple #12
0
def is_win_dumping_to_default():  # pylint: disable=too-complex
    """Check whether Windows minidumps are enabled and set to go to Windows' default location.

    Raises:
        OSError: Raises if querying for the DumpType key throws and it is unrelated to various issues,
                 e.g. the key not being present.

    Returns:
        bool: Returns True when Windows has dumping enabled, and is dumping to the default location, otherwise False
    """
    import winreg  # pylint: disable=import-error
    # For now, this code does not edit the Windows Registry because we tend to be in a 32-bit
    # version of Python and if one types in regedit in the Run dialog, opens up the 64-bit registry.
    # If writing a key, we most likely need to flush. For the moment, no keys are written.
    try:
        with winreg.OpenKey(winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE),
                            r"Software\Microsoft\Windows\Windows Error Reporting\LocalDumps",
                            # Read key from 64-bit registry, which also works for 32-bit
                            0, (winreg.KEY_WOW64_64KEY + winreg.KEY_READ)) as key:

            try:
                dump_type_reg_value = winreg.QueryValueEx(key, "DumpType")
                if not (dump_type_reg_value[0] == 1 and dump_type_reg_value[1] == winreg.REG_DWORD):
                    print(NO_DUMP_MSG)
                    return False
            except OSError as ex:
                if ex.errno == 2:  # pylint: disable=no-else-return
                    print(NO_DUMP_MSG)
                    return False
                else:
                    raise

            try:
                dump_folder_reg_value = winreg.QueryValueEx(key, "DumpFolder")
                # %LOCALAPPDATA%\CrashDumps is the default location.
                if not (dump_folder_reg_value[0] == r"%LOCALAPPDATA%\CrashDumps" and
                        dump_folder_reg_value[1] == winreg.REG_EXPAND_SZ):
                    print()
                    print(f"WARNING: Dumps are instead appearing at: {dump_folder_reg_value[0]} - "
                          f"all crashes will be uninteresting.")
                    print()
                    return False
            except OSError as ex:
                # If the key value cannot be found, the dumps will be put in the default location
                # pylint: disable=no-else-return
                if ex.errno == 2 and ex.strerror == "The system cannot find the file specified":
                    return True
                else:
                    raise

        return True
    except OSError as ex:
        # If the LocalDumps registry key cannot be found, dumps will be put in the default location.
        # pylint: disable=no-else-return
        if ex.errno == 2 and ex.strerror == "The system cannot find the file specified":
            print()
            print("WARNING: The registry key HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\"
                  "Windows\\Windows Error Reporting\\LocalDumps cannot be found.")
            print()
            return False
        else:
            raise
Exemple #13
0
def add_to_system_path(paths, allusers=True, path_env_var='PATH'):
    """Adds the requested paths to the system PATH variable.

       You must call broadcast_environment_settings_change() after you are finished
       manipulating the environment with this and other functions.

    """
    # Make sure it's a list
    if not issubclass(type(paths), list):
        paths = [paths]

    # Ensure all the paths are valid before we start messing with the
    # registry.
    new_paths = None
    for p in paths:
        p = path.abspath(p)
        if new_paths:
            new_paths = new_paths + os.pathsep + p
        else:
            new_paths = p

    if allusers:
        # All Users
        root, keyname = (
            reg.HKEY_LOCAL_MACHINE,
            r'SYSTEM\CurrentControlSet\Control\Session Manager\Environment')
    else:
        # Just Me
        root, keyname = (reg.HKEY_CURRENT_USER, r'Environment')

    key = reg.OpenKey(root, keyname, 0,
                      reg.KEY_QUERY_VALUE | reg.KEY_SET_VALUE)

    reg_type = None
    reg_value = None
    try:
        try:
            reg_value = reg.QueryValueEx(key, path_env_var)
        except WindowsError:
            # This will happen if we're a non-admin install and the user has
            # no PATH variable; in which case, we can write our new paths
            # directly.
            reg_type = reg.REG_EXPAND_SZ
            final_value = new_paths
        else:
            # Put to the front of PATH irrespective of allusers. The old
            # behaviour was asking for trouble and did not, contrary to what
            # this comment used to say, mirror what happens on *nix.
            reg_type = reg_value[1]
            final_value = new_paths + os.pathsep + reg_value[0]
        # Replace coincident ';' with a single ';'
        final_value = re.sub(r'([\;])+', r'\1', final_value)
        # Remove trailing ';'
        final_value = re.sub(r'\;$', '', final_value)
        # Remove any '"', they are not needed and break conda.
        final_value = final_value.replace('"', '')
        # Warn about directories that do not exist.
        directories = final_value.split(';')
        for directory in directories:
            if '%' not in directory and not os.path.exists(directory):
                out("WARNING: Old PATH entry '%s' does not exist\n" %
                    (directory))
        reg.SetValueEx(key, path_env_var, 0, reg_type, final_value)

    finally:
        reg.CloseKey(key)
Exemple #14
0
    'qt': '其它',
    'w': '无微聊',
    '': '',
    'save': 'save',
    'q': 'quit',
    'c': 'correct'
}
print("审核规则:", end='')
print(
    "['x':'吸粉','f':'否','y':'引流','s':'涉黄','sz':'刷钻','sc':'首次','qz':'欺诈','qt':'其它','w':'无微聊','c':'修改','save':'临时保存','q':'退出']"
)
real_address = winreg.OpenKey(
    winreg.HKEY_CURRENT_USER,
    r'Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders',
)
file_address = winreg.QueryValueEx(real_address, "Desktop")[0]
file_address += '\\'
file = input('请输入审核文件名称(无需添加后缀.xlsx或者.xls):')
filename = file_address + file + ".xlsx"
while True:
    try:
        wb = xlrd.open_workbook(filename)
    except FileNotFoundError:
        file = input('桌面查找不到该文件,请重新输入审核文件名称(请添加后缀.xlsx或者.xls):')
        filename = file_address + file
    else:
        break
rb = copy(wb)
sheet_number = input("请输入查询第几页:")
active = True
while active:
Exemple #15
0
 def read_player_cfg(cls, auto_keys=None):
     import winreg
     subkey = f"Software\\{cls.name.upper()}\\Settings"
     hkey = winreg.OpenKey(winreg.HKEY_CURRENT_USER, subkey)
     return {"port": lambda: winreg.QueryValueEx(hkey, "WebServerPort")[0]}
Exemple #16
0
def load_config():
    config_dict = {}

    if os.path.isfile(CONFIG_FILEPATH):
        try:
            with open(CONFIG_FILEPATH, 'rb') as f:
                config_dict = pickle.load(f)
        except:
            print('[ERROR]: Can not read config from %s' % CONFIG_FILEPATH)

    for tag in _CONFIG_DEFAULTS_ALL:
        if tag not in config_dict:
            config_dict[tag] = _CONFIG_DEFAULTS_ALL[tag]

    for tag in _CONFIG_TAGS_:
        if tag not in config_dict:
            if sys.platform.startswith('win'):
                config_dict[tag] = _CONFIG_DEFAULTS_WINDOWS[tag]
            elif sys.platform.startswith('linux') or sys.platform.startswith(
                    'darwin') or sys.platform.startswith('freebsd'):
                config_dict[tag] = _CONFIG_DEFAULTS_UNIX[tag]
            else:
                print('ERROR: unknown platform')
                assert 0

    try:
        if sys.platform.startswith('win'):
            import winreg
            # Find the blender2ogre install path from windows registry
            registry_key = winreg.OpenKey(winreg.HKEY_CLASSES_ROOT,
                                          r'Software\blender2ogre', 0,
                                          winreg.KEY_READ)
            exe_install_dir = winreg.QueryValueEx(registry_key, "Path")[0]
            if exe_install_dir != "":
                # OgreXmlConverter
                if os.path.isfile(exe_install_dir + "OgreXmlConverter.exe"):
                    print("Using OgreXmlConverter from install path:",
                          exe_install_dir + "OgreXmlConverter.exe")
                    config_dict[
                        'OGRETOOLS_XML_CONVERTER'] = exe_install_dir + "OgreXmlConverter.exe"
                # Run auto updater as silent. Notifies user if there is a new version out.
                # This will not show any UI if there are no update and will go to network
                # only once per 2 days so it wont be spending much resources either.
                # todo: Move this to a more appropriate place than load_config()
                if os.path.isfile(exe_install_dir + "check-for-updates.exe"):
                    subprocess.Popen(
                        [exe_install_dir + "check-for-updates.exe", "/silent"])
    except Exception as e:
        print("Exception while reading windows registry:", e)

    # Setup temp hidden RNA to expose the file paths
    for tag in _CONFIG_TAGS_:
        default = config_dict[tag]
        #func = eval( 'lambda self,con: config_dict.update( {"%s" : self.%s} )' %(tag,tag) )
        func = lambda self, con: config_dict.update(
            {tag: getattr(self, tag, default)})
        if type(default) is bool:
            prop = BoolProperty(name=tag,
                                description='updates bool setting',
                                default=default,
                                options={'SKIP_SAVE'},
                                update=func)
        else:
            prop = StringProperty(name=tag,
                                  description='updates path setting',
                                  maxlen=128,
                                  default=default,
                                  options={'SKIP_SAVE'},
                                  update=func)
        setattr(bpy.types.WindowManager, tag, prop)

    return config_dict
Exemple #17
0
def build_windows():
    """Build windows executables/setups."""
    utils.print_title("Updating 3rdparty content")
    # Currently disabled because QtWebEngine has no pdfjs support
    # update_3rdparty.run(ace=False, pdfjs=True, fancy_dmg=False)

    utils.print_title("Building Windows binaries")
    parts = str(sys.version_info.major), str(sys.version_info.minor)
    ver = ''.join(parts)
    dot_ver = '.'.join(parts)

    # Get python path from registry if possible
    try:
        reg64_key = winreg.OpenKeyEx(
            winreg.HKEY_LOCAL_MACHINE, r'SOFTWARE\Python\PythonCore'
            r'\{}\InstallPath'.format(dot_ver))
        python_x64 = winreg.QueryValueEx(reg64_key, 'ExecutablePath')[0]
    except FileNotFoundError:
        python_x64 = r'C:\Python{}\python.exe'.format(ver)

    try:
        reg32_key = winreg.OpenKeyEx(
            winreg.HKEY_LOCAL_MACHINE,
            r'SOFTWARE\WOW6432Node\Python\PythonCore'
            r'\{}-32\InstallPath'.format(dot_ver))
        python_x86 = winreg.QueryValueEx(reg32_key, 'ExecutablePath')[0]
    except FileNotFoundError:
        python_x86 = r'C:\Python{}-32\python.exe'.format(ver)

    out_pyinstaller = os.path.join('dist', 'qutebrowser')
    out_32 = os.path.join('dist',
                          'qutebrowser-{}-x86'.format(qutebrowser.__version__))
    out_64 = os.path.join('dist',
                          'qutebrowser-{}-x64'.format(qutebrowser.__version__))

    artifacts = []

    utils.print_title("Updating VersionInfo file")
    gen_versioninfo.main()

    utils.print_title("Running pyinstaller 32bit")
    _maybe_remove(out_32)
    call_tox('pyinstaller', '-r', python=python_x86)
    shutil.move(out_pyinstaller, out_32)
    patch_windows(out_32)

    utils.print_title("Running pyinstaller 64bit")
    _maybe_remove(out_64)
    call_tox('pyinstaller', '-r', python=python_x64)
    shutil.move(out_pyinstaller, out_64)
    patch_windows(out_64)

    utils.print_title("Building installers")
    subprocess.run([
        'makensis.exe', '/DVERSION={}'.format(qutebrowser.__version__),
        'misc/qutebrowser.nsi'
    ],
                   check=True)
    subprocess.run([
        'makensis.exe', '/DX64', '/DVERSION={}'.format(
            qutebrowser.__version__), 'misc/qutebrowser.nsi'
    ],
                   check=True)

    name_32 = 'qutebrowser-{}-win32.exe'.format(qutebrowser.__version__)
    name_64 = 'qutebrowser-{}-amd64.exe'.format(qutebrowser.__version__)

    artifacts += [
        (os.path.join('dist', name_32),
         'application/vnd.microsoft.portable-executable',
         'Windows 32bit installer'),
        (os.path.join('dist', name_64),
         'application/vnd.microsoft.portable-executable',
         'Windows 64bit installer'),
    ]

    utils.print_title("Running 32bit smoke test")
    smoke_test(os.path.join(out_32, 'qutebrowser.exe'))
    utils.print_title("Running 64bit smoke test")
    smoke_test(os.path.join(out_64, 'qutebrowser.exe'))

    utils.print_title("Zipping 32bit standalone...")
    name = 'qutebrowser-{}-windows-standalone-win32'.format(
        qutebrowser.__version__)
    shutil.make_archive(name, 'zip', 'dist', os.path.basename(out_32))
    artifacts.append(
        ('{}.zip'.format(name), 'application/zip', 'Windows 32bit standalone'))

    utils.print_title("Zipping 64bit standalone...")
    name = 'qutebrowser-{}-windows-standalone-amd64'.format(
        qutebrowser.__version__)
    shutil.make_archive(name, 'zip', 'dist', os.path.basename(out_64))
    artifacts.append(
        ('{}.zip'.format(name), 'application/zip', 'Windows 64bit standalone'))

    return artifacts
Exemple #18
0
import sys
import time

# GUIelements:
from GUI.mainwindow2 import Ui_MainWindow
from GUI import element_table_Qt5 as et

version = '0.9.0'

program_path = os.path.dirname(__file__)
if os.name == 'nt':
    import winreg
    try:
        with winreg.OpenKey(winreg.HKEY_CURRENT_USER,
                            r"SOFTWARE\Cameca\SX\Configuration") as thingy:
            data_path = winreg.QueryValueEx(thingy, "DataPath")[0]
        qtiSet_path = os.path.join(data_path, 'Analysis Setups', 'Quanti')
    except EnvironmentError:
        logging.warning(
            'Cameca PeakSight sotware were not dected on the system')

# for development and debugging on linux/bsd:
elif os.name == 'posix':
    # the path with sample qtiSet files
    qtiSet_path = 'Quanti'

with open(os.path.join(program_path, 'about.html'), 'r') as about_html:
    about_text = about_html.read()


# handy functions:
Exemple #19
0
        progress_var.set('Success (' + str(percentage_of_completion) + '%)')

        # 恢復按鈕
        download_button.config(state='normal')

    window.update()


# 版本號
version = '(0.0.0.1)'

# 取得桌面路徑
winreg_key = winreg.OpenKey(
    winreg.HKEY_CURRENT_USER,
    'Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders')
desktop_path = winreg.QueryValueEx(winreg_key, 'Desktop')[0]

# 建立 tkinter 物件
window = Tk()
window.title('Youtube to mp4 ' + version)

# 視窗寬與高
w = 800
h = 100

# 取得螢幕寬與高
window_width = window.winfo_screenwidth()
window_height = window.winfo_screenheight()

# 計算 x 與 y 位置
x = int(window_width / 2) - int(w / 2)
Exemple #20
0
    def send_dhcp_req(self, debug, donotaddtoenv, outputregistry):
        """
        Build dhcp request with mac addr
        Configure route to allow dhcp traffic
        Stop dhcp service if necessary
        """
        if debug == True:
            print("Sending dhcp request")
        mac_addr = self.osutil.get_mac_in_bytes()

        if debug == True:
            print('Mac address', mac_addr)

        req = build_dhcp_request(mac_addr, self._request_broadcast, debug)

        resp = self._send_dhcp_req(req, debug)

        if resp is None:
            raise DhcpError("Failed to receive dhcp response.")
        self.endpoint, self.gateway, self.routes = parse_dhcp_resp(resp, debug)
        print('Scheduled Events endpoint IP address:', self.endpoint)

        env_var = "SCHEDULEDEVENTSIP"
        env_val = self.endpoint
        if donotaddtoenv == False:
            print('Adding Scheduled Events endpoint IP to the environment')
            if sys.platform == 'win32':
                os.system("SETX {0} {1} /M".format(env_var, env_val))

            elif "linux" in sys.platform:
                # Set the scheduled events IP address in the environment for the
                # current process
                os.environ['SCHEDULEDEVENTSIP'] = self.endpoint

                # Set the scheduled events IP address in the environment for all users
                # This is done by reading the file /etc/profile line by line
                # Looking for a match to "export SCHEDULEDEVENTSIP="
                # Writing the same file again excluding that line and appending that line again
                # With the correct value of the IP address
                f = open("/etc/profile", 'r')
                match = "export SCHEDULEDEVENTSIP="
                lines = f.readlines()
                f.close()

                f = open("/etc/profile", 'w')
                for line in lines:
                    if match not in line:
                        f.write(line)
                f.write("export {0}={1}\n".format(env_var, env_val))
                f.close()
            else:
                print(
                    'Unknown operating system detected. Cannot add the scheduled events IP to the environment')
        if outputregistry == True and sys.platform == 'win32':
            print(
                'Adding Scheduled Events endpoint to registry location HKEY_LOCAL_MACHINE\\Software\\ScheduledEvents')
            key = wreg.CreateKey(wreg.HKEY_LOCAL_MACHINE,
                                 "Software\\ScheduledEvents")
            # Create new value
            wreg.SetValueEx(key, 'ScheduledEventsIp', 0,
                            wreg.REG_SZ, self.endpoint)
            print(wreg.QueryValueEx(key, 'ScheduledEventsIp'))
            key.Close()
Exemple #21
0
    def try_open(self, url, browser):
        import subprocess

        if sublime.platform() == 'windows':
            import winreg

        browser = browser.lower().strip()
        items = []

        if browser == 'chrome':
            if sublime.platform() == 'osx':
                items.extend(['open'])
                commands = ['-a', '/Applications/Google Chrome.app', url]
            elif sublime.platform() == 'windows':
                aKey = winreg.OpenKey(
                    winreg.HKEY_CURRENT_USER,
                    r"Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders"
                )
                reg_value, reg_type = winreg.QueryValueEx(
                    aKey, "Local AppData")

                items.extend([
                    '%HOMEPATH%\\AppData\\Local\\Google\\Chrome\\Application\\chrome.exe',
                    reg_value + '\\Chrome\\Application\\chrome.exe',
                    reg_value + '\\Google\\Chrome\\Application\\chrome.exe',
                    '%HOMEPATH%\\Google\\Chrome\\Application\\chrome.exe',
                    '%PROGRAMFILES%\\Google\\Chrome\\Application\\chrome.exe',
                    '%PROGRAMFILES(X86)%\\Google\\Chrome\\Application\\chrome.exe',
                    '%USERPROFILE%\\Local\ Settings\\Application\ Data\\Google\\Chrome\\chrome.exe',
                    '%HOMEPATH%\\Chromium\\Application\\chrome.exe',
                    '%PROGRAMFILES%\\Chromium\\Application\\chrome.exe',
                    '%PROGRAMFILES(X86)%\\Chromium\\Application\\chrome.exe',
                    '%HOMEPATH%\\Local\ Settings\\Application\ Data\\Google\\Chrome\\Application\\chrome.exe',
                    '%HOMEPATH%\\Local Settings\\Application Data\\Google\\Chrome\\Application\\chrome.exe',
                    'chrome.exe'
                ])

                commands = ['-new-tab', url]
            else:
                items.extend([
                    '/usr/bin/google-chrome', '/opt/google/chrome/chrome',
                    'chrome', 'google-chrome'
                ])
                commands = ['-new-tab', url]

        elif browser == 'canary':
            if sublime.platform() == 'osx':
                items.extend(['open'])
                commands = [
                    '-a', '/Applications/Google Chrome Canary.app', url
                ]
            elif sublime.platform() == 'windows':
                aKey = winreg.OpenKey(
                    winreg.HKEY_CURRENT_USER,
                    r"Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders"
                )
                reg_value, reg_type = winreg.QueryValueEx(
                    aKey, "Local AppData")

                items.extend([
                    '%HOMEPATH%\\AppData\\Local\\Google\\Chrome SxS\\Application\\chrome.exe',
                    reg_value + '\\Chrome SxS\\Application\\chrome.exe',
                    reg_value +
                    '\\Google\\Chrome SxS\\Application\\chrome.exe',
                    '%HOMEPATH%\\Google\\Chrome SxS\\Application\\chrome.exe',
                    '%PROGRAMFILES%\\Google\\Chrome SxS\\Application\\chrome.exe',
                    '%PROGRAMFILES(X86)%\\Google\\Chrome SxS\\Application\\chrome.exe',
                    '%USERPROFILE%\\Local\ Settings\\Application\ Data\\Google\\Chrome SxS\\chrome.exe',
                    '%HOMEPATH%\\Local\ Settings\\Application\ Data\\Google\\Chrome SxS\\Application\\chrome.exe',
                    '%HOMEPATH%\\Local Settings\\Application Data\\Google\\Chrome SxS\\Application\\chrome.exe'
                ])

                commands = ['-new-tab', url]

        elif browser == 'chromium':
            if sublime.platform() == 'osx':
                items.extend(['open'])
                commands = ['-a', '/Applications/Chromium.app', url]
            elif sublime.platform() == 'windows':
                aKey = winreg.OpenKey(
                    winreg.HKEY_CURRENT_USER,
                    r"Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders"
                )
                reg_value, reg_type = winreg.QueryValueEx(
                    aKey, "Local AppData")
                items.extend([
                    '%HOMEPATH%\\AppData\\Local\\Google\\Chrome SxS\\Application\\chrome.exe',
                    reg_value + '\\Chromium\\Application\\chromium.exe',
                    '%USERPROFILE%\\Local Settings\\Application Data\\Google\\Chrome\\chromium.exe',
                    '%USERPROFILE%\\Local\ Settings\\Application\ Data\\Google\\Chrome\\chromium.exe',
                    '%HOMEPATH%\\Chromium\\Application\\chromium.exe',
                    '%PROGRAMFILES%\\Chromium\\Application\\chromium.exe',
                    '%PROGRAMFILES(X86)%\\Chromium\\Application\\chromium.exe',
                    '%HOMEPATH%\\Local Settings\\Application\ Data\\Google\\Chrome\\Application\\chromium.exe',
                    '%HOMEPATH%\\Local Settings\\Application Data\\Google\\Chrome\\Application\\chromium.exe',
                    'chromium.exe',
                    reg_value + '\\Chromium\\Application\\chrome.exe',
                    '%USERPROFILE%\\Local Settings\\Application Data\\Google\\Chrome\\chrome.exe',
                    '%USERPROFILE%\\Local\ Settings\\Application\ Data\\Google\\Chrome\\chrome.exe',
                    '%HOMEPATH%\\Chromium\\Application\\chrome.exe',
                    '%PROGRAMFILES%\\Chromium\\Application\\chrome.exe',
                    '%PROGRAMFILES(X86)%\\Chromium\\Application\\chrome.exe',
                    '%HOMEPATH%\\Local\ Settings\\Application\ Data\\Google\\Chrome\\Application\\chrome.exe',
                    '%HOMEPATH%\\Local Settings\\Application Data\\Google\\Chrome\\Application\\chrome.exe',
                    'chrome.exe'
                ])
                commands = ['-new-tab', url]
            else:
                items.extend([
                    '/usr/bin/chromium', 'chromium',
                    '/usr/bin/chromium-browser', 'chromium-browser'
                ])
                commands = ['-new-tab', url]
        elif browser == 'firefox':
            if sublime.platform() == 'osx':
                items.extend(['open'])
                commands = ['-a', '/Applications/Firefox.app', url]
            else:
                items.extend([
                    '/usr/bin/firefox', '%PROGRAMFILES%\\Nightly\\firefox.exe',
                    '%PROGRAMFILES(X86)%\\Nightly\\firefox.exe',
                    '%PROGRAMFILES%\\Mozilla Firefox\\firefox.exe',
                    '%PROGRAMFILES(X86)%\\Mozilla Firefox\\firefox.exe',
                    'firefox', 'firefox.exe'
                ])
                commands = ['-new-tab', url]
        elif browser == 'aurora':
            if sublime.platform() == 'osx':
                items.extend(['open'])
                commands = ['-a', '/Applications/FirefoxAurora.app', url]
            else:
                items.extend([
                    '/usr/bin/aurora', '%PROGRAMFILES%\\Aurora\\firefox.exe',
                    '%PROGRAMFILES(X86)%\\Aurora\\firefox.exe', 'firefox',
                    'firefox.exe'
                ])
                commands = ['-new-tab', url]
        elif browser == 'opera':
            if sublime.platform() == 'osx':
                items.extend(['open'])
                commands = ['-a', '/Applications/Opera.app', url]
            else:
                items.extend([
                    '/usr/bin/opera', '/usr/bin/opera-next',
                    '/usr/bin/operamobile', '%PROGRAMFILES%\\Opera\\opera.exe',
                    '%PROGRAMFILES(X86)%\\Opera\\opera.exe',
                    '%PROGRAMFILES%\\Opera Next\\opera.exe',
                    '%PROGRAMFILES(X86)%\\Opera Next\\opera.exe',
                    '%PROGRAMFILES%\\Opera Mobile Emulator\\OperaMobileEmu.exe',
                    '%PROGRAMFILES(X86)%\\Opera Mobile Emulator\\OperaMobileEmu.exe',
                    'opera', 'opera.exe'
                ])
                commands = ['-newtab', url]
        elif browser == 'safari':
            if sublime.platform() == 'osx':
                items.extend(['open'])
                commands = ['-a', 'Safari', url]
            else:
                items.extend([
                    '/usr/bin/safari', '%PROGRAMFILES%\\Safari\\Safari.exe',
                    '%PROGRAMFILES(X86)%\\Safari\\Safari.exe', 'Safari',
                    'Safari.exe'
                ])
                commands = ['-new-tab', '-url', url]
        else:
            commands = ['-new-tab', url]

        for item in items:
            try:
                command2 = list(commands)
                command2.insert(0, expandVars(item))
                subprocess.Popen(command2)
                return
            except:
                try:
                    command2 = list(commands)
                    command2.insert(0, item)
                    subprocess.Popen(command2)
                    return
                except:
                    pass
        try:
            if sublime.platform() == 'windows':
                commands = ['cmd', '/c', 'start', '', url]
                subprocess.Popen(commands)
            elif sublime.platform() == 'linux':
                commands = ['xdg-open', url]
                subprocess.Popen(commands)
            else:
                commands = ['open', url]
                subprocess.Popen(commands)
            return
        except:
            pass

        sublime.error_message(
            'Can not open PayPal url. Default browser not found..')
Exemple #22
0
def getNookLogFiles():
    logFiles = []
    found = False
    if iswindows:
        import 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.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
Exemple #23
0
def nic_info():
    """列出所有NIC的信息
    :returns: NIC信息,类型为:

        {
            'iface': {
                'v4': [{info}],
                'v6': [{info}],
                'rsp' {iface_name: iface_ID}
            }
        }

    """
    nics = dict()

    # 获取所有NIC名的列表 -- Linux获取的是正常的NIC名,Windows获取的是NIC的ID
    ifaces = netifaces.interfaces()

    # Linux分支: 直出NIC信息
    if system == 'Linux':
        for iface in ifaces:
            iface_info = netifaces.ifaddresses(iface)  # 获取指定NIC的信息

            nic = dict()
            # IPv4信息
            nic['v4'] = iface_info.get(netifaces.AF_INET, [dict()])
            # IPv6信息
            nic['v6'] = iface_info.get(netifaces.AF_INET6, [dict()])
            # NIC Name和NIC ID的relationship
            nic['rsp'] = {iface: iface}
            nics[iface] = nic
    # Windows分支: 直出NIC ID,需要再以之得到NIC Name
    elif system == 'Windows':
        # Windows注册表中关于Network的一部分路径名,固定值
        NETWORK_KEY = '{4D36E972-E325-11CE-BFC1-08002BE10318}'
        path = r'SYSTEM\CurrentControlSet\Control\Network\{}'.format(
            NETWORK_KEY)
        # 根据NIC ID从注册表获取NIC Name
        try:
            # 连接到注册表HKEY_LOCAL_MACHINE,None表示本地计算机
            registry = winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE)
            registry_network = winreg.OpenKey(registry, path)
        except Exception as e:
            raise e

        for iface_id in ifaces:
            iface_info = netifaces.ifaddresses(iface_id)  # 获取指定NIC的信息

            sub_path = r'{}\{}'.format(iface_id, 'Connection')
            try:
                registry_nic = winreg.OpenKey(registry_network, sub_path)
                iface_name = winreg.QueryValueEx(registry_nic, 'Name')[0]
            except FileNotFoundError:
                continue

            nic = dict()
            # IPv4信息
            nic['v4'] = iface_info.get(netifaces.AF_INET, [dict()])
            # IPv6信息
            nic['v6'] = iface_info.get(netifaces.AF_INET6, [dict()])
            # NIC Name和NIC ID的relationship
            nic['rsp'] = {iface_name: iface_id}
            nics[iface_name] = nic
    else:
        raise OSError('当前仅支持{}系统,该系统不受支持'.format('Linux/Windows'))

    return nics
Exemple #24
0
_wsh = None


def _getWSH():
    global _wsh
    if not _wsh:
        import comtypes.client
        _wsh = comtypes.client.CreateObject("wScript.Shell", dynamic=True)
    return _wsh


defaultStartMenuFolder = versionInfo.name
with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE,
                    "SOFTWARE\Microsoft\Windows\CurrentVersion") as k:
    programFilesPath = winreg.QueryValueEx(k, "ProgramFilesDir")[0]
defaultInstallPath = os.path.join(programFilesPath, versionInfo.name)


def createShortcut(path,
                   targetPath=None,
                   arguments=None,
                   iconLocation=None,
                   workingDirectory=None,
                   hotkey=None,
                   prependSpecialFolder=None):
    # #7696: The shortcut is only physically saved to disk if it does not already exist, or one or more properties have changed.
    wsh = _getWSH()
    if prependSpecialFolder:
        specialPath = wsh.SpecialFolders(prependSpecialFolder)
        path = os.path.join(specialPath, path)
Exemple #25
0
    def on_user_logged_in(sender, user):
        # Keep hold of the user ID
        user_id = user.id

        # Get the first server group for the user
        servergroup_id = 1
        servergroups = ServerGroup.query.filter_by(
            user_id=user_id).order_by("id")

        if servergroups.count() > 0:
            servergroup = servergroups.first()
            servergroup_id = servergroup.id
        '''Add a server to the config database'''
        def add_server(user_id, servergroup_id, name, superuser, port,
                       discovery_id, comment):
            # Create a server object if needed, and store it.
            servers = Server.query.filter_by(
                user_id=user_id, discovery_id=svr_discovery_id).order_by("id")

            if servers.count() > 0:
                return

            svr = Server(user_id=user_id,
                         servergroup_id=servergroup_id,
                         name=name,
                         host='localhost',
                         port=port,
                         maintenance_db='postgres',
                         username=superuser,
                         ssl_mode='prefer',
                         comment=svr_comment,
                         discovery_id=discovery_id)

            db.session.add(svr)
            db.session.commit()

        # Figure out what servers are present
        if winreg is not None:
            arch_keys = set()
            proc_arch = os.environ['PROCESSOR_ARCHITECTURE'].lower()

            try:
                proc_arch64 = os.environ['PROCESSOR_ARCHITEW6432'].lower()
            except:
                proc_arch64 = None

            if proc_arch == 'x86' and not proc_arch64:
                arch_keys.add(0)
            elif proc_arch == 'x86' or proc_arch == 'amd64':
                arch_keys.add(winreg.KEY_WOW64_32KEY)
                arch_keys.add(winreg.KEY_WOW64_64KEY)

            for arch_key in arch_keys:
                for server_type in ('PostgreSQL', 'EnterpriseDB'):
                    try:
                        root_key = winreg.OpenKey(
                            winreg.HKEY_LOCAL_MACHINE,
                            "SOFTWARE\\" + server_type + "\Services", 0,
                            winreg.KEY_READ | arch_key)
                        for i in xrange(0, winreg.QueryInfoKey(root_key)[0]):
                            inst_id = winreg.EnumKey(root_key, i)
                            inst_key = winreg.OpenKey(root_key, inst_id)

                            svr_name = winreg.QueryValueEx(
                                inst_key, 'Display Name')[0]
                            svr_superuser = winreg.QueryValueEx(
                                inst_key, 'Database Superuser')[0]
                            svr_port = winreg.QueryValueEx(inst_key, 'Port')[0]
                            svr_discovery_id = inst_id
                            svr_comment = gettext(
                                "Auto-detected %s installation with the data directory at %s"
                                % (winreg.QueryValueEx(inst_key,
                                                       'Display Name')[0],
                                   winreg.QueryValueEx(inst_key,
                                                       'Data Directory')[0]))

                            add_server(user_id, servergroup_id, svr_name,
                                       svr_superuser, svr_port,
                                       svr_discovery_id, svr_comment)

                            inst_key.Close()
                    except:
                        pass
        else:
            # We use the postgres-winreg.ini file on non-Windows
            try:
                from configparser import ConfigParser
            except ImportError:
                from ConfigParser import ConfigParser  # Python 2

            registry = ConfigParser()

        try:
            registry.read('/etc/postgres-reg.ini')
            sections = registry.sections()

            # Loop the sections, and get the data from any that are PG or PPAS
            for section in sections:
                if section.startswith('PostgreSQL/') or section.startswith(
                        'EnterpriseDB/'):
                    svr_name = registry.get(section, 'Description')
                    svr_superuser = registry.get(section, 'Superuser')
                    svr_port = registry.getint(section, 'Port')
                    svr_discovery_id = section
                    description = registry.get(section, 'Description')
                    data_directory = registry.get(section, 'DataDirectory')
                    if hasattr(str, 'decode'):
                        description = description.decode('utf-8')
                        data_directory = data_directory.decode('utf-8')
                    svr_comment = gettext(
                        u"Auto-detected %s installation with the data directory at %s"
                        % (description, data_directory))
                    add_server(user_id, servergroup_id, svr_name,
                               svr_superuser, svr_port, svr_discovery_id,
                               svr_comment)

        except:
            pass
Exemple #26
0
def get_desktop():
    key = winreg.OpenKey(
        winreg.HKEY_CURRENT_USER,
        r'Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders')
    return winreg.QueryValueEx(key, "Desktop")[0]
Exemple #27
0
def get_vsdir(version="15.0"):
    with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE
            , "SOFTWARE\\WOW6432Node\\Microsoft\\VisualStudio\\SxS\\VS7") as key:
        return winreg.QueryValueEx(key, '15.0')[0]
Exemple #28
0
def lacate_folder(name='Personal'):
    """Personal Recent
    """
    key = winreg.OpenKey(winreg.HKEY_CURRENT_USER,
        r'Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders')
    return winreg.QueryValueEx(key, name)[0]  # dir, type
Modified to use the 'HotSpotImageFolderPath' and search for the latest 
large landscape image, since the previous version didn't show the most 
recently displayed lock image.

jdpipe 2021
'''
try:
    # Connect to registry, set appropriate key.
    reg = winreg.ConnectRegistry(None, winreg.HKEY_CURRENT_USER)
    reg = winreg.OpenKey(
        reg,
        r"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Lock Screen\\Creative")

    # Fetch Registry value (file path) for LandscapeAssetPath.
    regKey = winreg.QueryValueEx(reg, 'HotSpotImageFolderPath')[0]

    # Normalize filepath.
    imgDir = os.path.normpath(regKey)
except Exception as e:
    print("{}".format(e.message))
    sys.exit('Something went wrong relating to the filesystem.')

try:
    ls = pathlib.Path(imgDir).glob('*')
    ls = [str(i) for i in ls if check_landscape(i)]
    ls = sorted(ls, key=os.path.getmtime)
    ls.reverse()
    #print("\n".join([repr((i,os.path.getmtime(i))) for i in ls]))
    #sp.run("ls -lahS %s"%(imgDir,),shell=True,check=True)
except Exception as e:
Exemple #30
0
                                 Path to destination vmx file
                                 full|linked
                                 [Snapshot name]
        """
        return self.do('clone', dest_vmx, mode, snap_name)


if sys.platform == "win32":
    # get vmrun.exe's full path via registry
    import winreg

    reg = winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE)
    try:
        rh = winreg.OpenKey(reg, r'SOFTWARE\VMware, Inc.\VMware Workstation')
        try:
            vw_dir = winreg.QueryValueEx(rh, 'InstallPath')[0]
        finally:
            winreg.CloseKey(rh)
    finally:
        reg.Close()

    if vw_dir != '':
        VMRUN_PATH = vw_dir + 'vmrun.exe'
else:
    if "PATH" in os.environ:
        for path in os.environ["PATH"].split(os.pathsep):
            tmp_file = path + os.sep + "vmrun"
            if os.path.exists(tmp_file):
                VMRUN_PATH = tmp_file
                break
        # escape spaces in path