Пример #1
0
    def _load_machine_vars(self) -> None:
        """Load machine vars from data manager."""
        self.machine_var_data_manager = self.create_data_manager(
            'machine_vars')

        current_time = self.clock.get_time()

        for name, settings in (iter(
                self.machine_var_data_manager.get_data().items())):

            if not isinstance(settings, dict) or "value" not in settings:
                continue

            if ('expire' in settings and settings['expire']
                    and settings['expire'] < current_time):

                settings['value'] = 0

            self.set_machine_var(name=name, value=settings['value'])

        self._load_initial_machine_vars()

        # Create basic system information machine variables
        self.set_machine_var(name="mpf_version", value=mpf_version)
        self.set_machine_var(name="mpf_extended_version",
                             value=mpf_extended_version)
        self.set_machine_var(name="python_version", value=python_version())
        self.set_machine_var(name="platform", value=platform(aliased=True))
        platform_info = system_alias(system(), release(), version())
        self.set_machine_var(name="platform_system", value=platform_info[0])
        self.set_machine_var(name="platform_release", value=platform_info[1])
        self.set_machine_var(name="platform_version", value=platform_info[2])
        self.set_machine_var(name="platform_machine", value=machine())
Пример #2
0
def print_basic_debug_info(out=None):
    if out is None:
        out = sys.stdout
    out = functools.partial(prints, file=out)
    import platform
    from calibre.constants import (__appname__, get_version, isportable, isosx,
                                   isfrozen, is64bit)
    out(__appname__, get_version(), 'Portable' if isportable else '',
        'embedded-python:', isfrozen, 'is64bit:', is64bit)
    out(platform.platform(), platform.system(), platform.architecture())
    if iswindows and not is64bit:
        try:
            import win32process
            if win32process.IsWow64Process():
                out('32bit process running on 64bit windows')
        except:
            pass
    out(platform.system_alias(platform.system(), platform.release(),
            platform.version()))
    out('Python', platform.python_version())
    try:
        if iswindows:
            out('Windows:', platform.win32_ver())
        elif isosx:
            out('OSX:', platform.mac_ver())
        else:
            out('Linux:', platform.linux_distribution())
    except:
        pass
    from calibre.customize.ui import has_external_plugins, initialized_plugins
    if has_external_plugins():
        names = (p.name for p in initialized_plugins() if getattr(p, 'plugin_path', None) is not None)
        out('Successfully initialized third party plugins:', ' && '.join(names))
Пример #3
0
    def report_failure(self, name, msg, show_traceback=True):
        "Report a test failure, with some useful context."

        orig_tb = _traceback.extract_tb(_sys.exc_info()[2])
        tb = orig_tb

        # Move up the traceback until we get to the line in the test
        # function which caused the failure.
        while tb[-1][2] != "test_" + name:
            tb = tb[:-1]

        # Display the context in the text function.
        filepath, linenum, functionname, text = tb[-1]
        filename = _os.path.basename(filepath)

        self._out.ensure_space()
        self._out.write_colour("#red#FAILED##\n")
        if self._verbose > 0:
            if self._context is None:
                context = ""
            else:
                context = ", when %s" % self._context
            firstline = "%s:%d" % (filename, linenum)
            self._out.write("\n%s:%s%s\n" % (firstline, msg, context))

            # Display sourcecode lines
            lines = open(filepath).readlines()
            startline = max(linenum - 3, 0)
            endline = min(linenum + 2, len(lines))
            for num in range(startline, endline):
                if num + 1 == linenum:
                    self._out.write("->")
                else:
                    self._out.write("  ")
                self._out.write("%4d %s\n" % (num + 1, lines[num].rstrip()))

            # Display the traceback
            if show_traceback:
                self._out.write("Traceback (most recent call last):\n")
                for line in _traceback.format_list(orig_tb):
                    self._out.write(line.rstrip() + "\n")
                self._out.write("\n")

            # Display some information about the xapian version and platform
            self._out.write("Xapian version: %s\n" % _xapian.version_string())
            try:
                import platform

                platdesc = "%s %s (%s)" % platform.system_alias(
                    platform.system(), platform.release(), platform.version()
                )
                self._out.write("Platform: %s\n" % platdesc)
            except:
                pass
            self._out.write(
                '\nWhen reporting this problem, please quote all the preceding lines from\n"%s" onwards.\n\n'
                % firstline
            )

        self._out.flush()
Пример #4
0
def print_basic_debug_info(out=None):
    if out is None:
        out = sys.stdout
    out = functools.partial(prints, file=out)
    import platform
    from calibre.constants import (__appname__, get_version, isportable, isosx,
                                   isfrozen, is64bit)
    out(__appname__, get_version(), 'Portable' if isportable else '',
        'embedded-python:', isfrozen, 'is64bit:', is64bit)
    out(platform.platform(), platform.system(), platform.architecture())
    if iswindows and not is64bit:
        try:
            import win32process
            if win32process.IsWow64Process():
                out('32bit process running on 64bit windows')
        except:
            pass
    out(platform.system_alias(platform.system(), platform.release(),
            platform.version()))
    out('Python', platform.python_version())
    try:
        if iswindows:
            out('Windows:', platform.win32_ver())
        elif isosx:
            out('OSX:', platform.mac_ver())
        else:
            out('Linux:', platform.linux_distribution())
    except:
        pass
    from calibre.customize.ui import has_external_plugins, initialized_plugins
    if has_external_plugins():
        names = (p.name for p in initialized_plugins() if getattr(p, 'plugin_path', None) is not None)
        out('Successfully initialized third party plugins:', ' && '.join(names))
Пример #5
0
def print_basic_debug_info(out=None):
    if out is None:
        out = sys.stdout
    out = functools.partial(prints, file=out)
    import platform
    from calibre.constants import (__appname__, get_version, isportable, isosx,
                                   isfrozen, is64bit)
    out(__appname__, get_version(), 'Portable' if isportable else '',
        'isfrozen:', isfrozen, 'is64bit:', is64bit)
    out(platform.platform(), platform.system(), platform.architecture())
    if iswindows and not is64bit:
        try:
            import win32process
            if win32process.IsWow64Process():
                out('32bit process running on 64bit windows')
        except:
            pass
    out(
        platform.system_alias(platform.system(), platform.release(),
                              platform.version()))
    out('Python', platform.python_version())
    try:
        if iswindows:
            out('Windows:', platform.win32_ver())
        elif isosx:
            out('OSX:', platform.mac_ver())
        else:
            out('Linux:', platform.linux_distribution())
    except:
        pass
Пример #6
0
def get_env_info():
    '''Gets general information about the computer.'''
    
    infodict = OrderedDict()
    
    infodict["Name"] = platform.node()
    infodict["System"] = platform.system()
    infodict["System alias"] = " ".join(platform.system_alias(
            platform.system(), platform.release(), platform.version()))
    infodict["Platform"] = platform.platform()
    
    if infodict["System"] == "Linux": # System-specific information
        infodict["Distribution"] = " ".join(platform.dist())
    elif infodict["System"] == "Windows":
        infodict["OS"] = " ".join(platform.win32_ver())
    elif infodict["System"] == "MacOS":
        verinfo = platform.mac_ver()[1]
        macver = " ".join(platform.mac_ver())
        macver[1] = verinfo
        infodict["OS"] = " ".join(macver)
    
    infodict["Boot time"] = datetime.datetime.fromtimestamp(
            psutil.get_boot_time()).strftime("%c")
    infodict["Uptime"] = str(datetime.datetime.fromtimestamp(
            time.time() - psutil.get_boot_time()).strftime("%d:%H:%M:%S:%f"))
    
    for user in psutil.get_users():
        infodict["User '" + user.name + "' terminal"] = user.terminal
        infodict["User '" + user.name + "' host"] = user.host
        infodict["User '" + user.name + "' started"] = str(
                datetime.datetime.fromtimestamp(user.started).strftime("%c"))
    
    return infodict
Пример #7
0
def get_os_info():
    """
    Get Operating System type/distribution and major version

    :returns: (os_name, os_version)
    :rtype: `tuple` of `str`
    """
    info = platform.system_alias(platform.system(), platform.release(),
                                 platform.version())
    os_type, os_ver, _ = info
    os_type = os_type.lower()
    if os_type.startswith('linux'):
        info = platform.linux_distribution()
        # On arch, platform.linux_distribution() is reportedly ('','',''),
        # so handle it defensively
        if info[0]:
            os_type = info[0]
        if info[1]:
            os_ver = info[1]
    elif os_type.startswith('darwin'):
        os_ver = subprocess.Popen(["sw_vers", "-productVersion"],
                                  stdout=subprocess.PIPE).communicate()[0]
        os_ver = os_ver.partition(".")[0]
    elif os_type.startswith('freebsd'):
        # eg "9.3-RC3-p1"
        os_ver = os_ver.partition("-")[0]
        os_ver = os_ver.partition(".")[0]
    elif platform.win32_ver()[1]:
        os_ver = platform.win32_ver()[1]
    else:
        # Cases known to fall here: Cygwin python
        os_ver = ''
    return os_type, os_ver
Пример #8
0
def print_basic_debug_info(out=None):
    if out is None:
        out = sys.stdout
    out = functools.partial(prints, file=out)
    import platform
    from calibre.constants import (__appname__, get_version, isportable, isosx,
                                   isfrozen, is64bit)
    out(__appname__, get_version(), 'Portable' if isportable else '',
        'isfrozen:', isfrozen, 'is64bit:', is64bit)
    out(platform.platform(), platform.system(), platform.architecture())
    if iswindows and not is64bit:
        try:
            import win32process
            if win32process.IsWow64Process():
                out('32bit process running on 64bit windows')
        except:
            pass
    out(platform.system_alias(platform.system(), platform.release(),
            platform.version()))
    out('Python', platform.python_version())
    try:
        if iswindows:
            out('Windows:', platform.win32_ver())
        elif isosx:
            out('OSX:', platform.mac_ver())
        else:
            out('Linux:', platform.linux_distribution())
    except:
        pass
Пример #9
0
def get_os_info():
    """
    Get Operating System type/distribution and major version

    :returns: (os_name, os_version)
    :rtype: `tuple` of `str`
    """
    info = platform.system_alias(platform.system(), platform.release(), platform.version())
    os_type, os_ver, _ = info
    os_type = os_type.lower()
    if os_type.startswith("linux"):
        info = platform.linux_distribution()
        # On arch, platform.linux_distribution() is reportedly ('','',''),
        # so handle it defensively
        if info[0]:
            os_type = info[0]
        if info[1]:
            os_ver = info[1]
    elif os_type.startswith("darwin"):
        os_ver = subprocess.Popen(["sw_vers", "-productVersion"], stdout=subprocess.PIPE).communicate()[0]
        os_ver = os_ver.partition(".")[0]
    elif os_type.startswith("freebsd"):
        # eg "9.3-RC3-p1"
        os_ver = os_ver.partition("-")[0]
        os_ver = os_ver.partition(".")[0]
    elif platform.win32_ver()[1]:
        os_ver = platform.win32_ver()[1]
    else:
        # Cases known to fall here: Cygwin python
        os_ver = ""
    return os_type, os_ver
Пример #10
0
    def _merge_sysinfo(self, parser, properties):
        """Merge the platform information properties into the configuration."""
        system, _, release, version, machine, processor = platform.uname()
        system, release, version = platform.system_alias(system, release,
                                                         version)
        self.properties['machine'] = machine
        self.properties['processor'] = processor
        self.properties['os'] = system
        self.properties['family'] = os.name
        self.properties['version'] = release

        mapping = {'machine': ('machine', 'name'),
                   'processor': ('machine', 'processor'),
                   'os': ('os', 'name'),
                   'family': ('os', 'family'),
                   'version': ('os', 'version')}
        for key, (section, option) in mapping.items():
            if parser.has_option(section, option):
                value = parser.get(section, option)
                if value is not None:
                    self.properties[key] = value

        if properties:
            for key, value in properties.items():
                if key in mapping:
                    self.properties[key] = value
Пример #11
0
def print_basic_debug_info(out=None):
    if out is None:
        out = sys.stdout
    out = functools.partial(prints, file=out)
    import platform
    from contextlib import suppress
    from calibre.constants import (__appname__, get_version, isportable, ismacos,
                                   isfrozen, is64bit)
    from calibre.utils.localization import set_translators
    out(__appname__, get_version(), 'Portable' if isportable else '',
        'embedded-python:', isfrozen, 'is64bit:', is64bit)
    out(platform.platform(), platform.system(), platform.architecture())
    if iswindows and not is64bit:
        from calibre_extensions.winutil import is_wow64_process
        with suppress(Exception):
            if is_wow64_process():
                out('32bit process running on 64bit windows')
    out(platform.system_alias(platform.system(), platform.release(),
            platform.version()))
    out('Python', platform.python_version())
    try:
        if iswindows:
            out('Windows:', platform.win32_ver())
        elif ismacos:
            out('OSX:', platform.mac_ver())
        else:
            out('Linux:', platform.linux_distribution())
    except:
        pass
    out('Interface language:', unicode_type(set_translators.lang))
    from calibre.customize.ui import has_external_plugins, initialized_plugins
    if has_external_plugins():
        names = ('{0} {1}'.format(p.name, p.version) for p in initialized_plugins() if getattr(p, 'plugin_path', None) is not None)
        out('Successfully initialized third party plugins:', ' && '.join(names))
Пример #12
0
def platform_select(options, test_platform=()):
    ''' Find the current platform 

    Matches the output from platform.system_alias, ``system``, ``release``
    and ``version`` against 0-3 regular expressions and returns the first
    match.

    Given that the platform is (from :func:`platform.system_alias`)::
        ('Linux', '2.6.9-11.ELsmp', '#1 SMP Fri May 20 18:26:27 EDT 2005')

    A list of options like this:
        [
            # Match system and release
            (['Linux', '2.6.\d\d.*'], 'linux_new'),

            # Match only system
            (['Linux'] , 'linux_generic'),
        ]

    Would return ``linux_generic``.

    :arg options: List of platforms to match against, every entry must have
                  the format::
                  (list([system match, [release match, [version match]]]), <return value>)

                  If the list is empty all platforms would match.
                  If more the one options match the first one is selected
    :arg test_platform: For testing purposes, send in a tuple in the same format
                        as :func:`platform.system_alias()` 
    '''

    if test_platform: 
        system, release, version = test_platform
    else:
        system, release, version = this_platform = platform.system_alias(
                                                    platform.system(), 
                                                    platform.release(), 
                                                    platform.version())
    for option in options:
        match, select = option

        # Create a list of None for the ignored system specifiers  
        match_padding = [None] * (3 - len(match))

        match_system, match_release, match_version =\
                (match + match_padding)

        if match_system and not re.match(match_system, system):
            continue

        if match_release and not re.match(match_release, release):
            continue

        if match_version and not re.match(match_version, version):
            continue

        return select

    return None
Пример #13
0
def run():
    # Well, this is easy.
    platform_info = platform.system_alias(platform.system(), platform.release(), platform.version())
    return {
        'OS': 'System: {} || Release: {} || Version: {}'.format(platform_info[0], platform_info[1], platform_info[2]),
        'CPU Type':  '{} x {}'.format(platform.processor(), multiprocessing.cpu_count()),

        }
Пример #14
0
class GenerationInfo:
    created: DateTime = field(default_factory=lambda: datetime.now())
    system_alias: Tuple[AnyStr, AnyStr, AnyStr] = field(
        default_factory=lambda: platform.system_alias(platform.system(
        ), platform.release(), platform.version()))
    python_version: AnyStr = field(
        default_factory=lambda: platform.python_version())
    config_vars: Dict[AnyStr, object] = field(
        default_factory=sysconfig.get_config_vars)
Пример #15
0
    def report_failure(self, name, msg, show_traceback=True):
        "Report a test failure, with some useful context."

        tb = _traceback.extract_tb(_sys.exc_info()[2])

        # Move up the traceback until we get to the line in the test
        # function which caused the failure.
        for line in xrange(1, len(tb) + 1):
            if tb[-line][2] == 'test_' + name:
                break

        # Display the context in the text function.
        filepath, linenum, functionname, text = tb[-line]
        filename = _os.path.basename(filepath)

        self._out.ensure_space()
        self._out.write_colour("#red#FAILED##\n")
        if self._verbose > 0:
            if self._context is None:
                context = ''
            else:
                context = ", when %s" % self._context
            firstline = "%s:%d" % (filename, linenum)
            self._out.write("\n%s:%s%s\n" % (firstline, msg, context))

            # Display sourcecode lines
            lines = open(filepath).readlines()
            startline = max(linenum - 3, 0)
            endline = min(linenum + 2, len(lines))
            for num in range(startline, endline):
                if num + 1 == linenum:
                    self._out.write('->')
                else:
                    self._out.write('  ')
                self._out.write("%4d %s\n" % (num + 1, lines[num].rstrip()))

            # Display the traceback
            if show_traceback:
                self._out.write("Traceback (most recent call last):\n")
                for line in _traceback.format_list(tb):
                    self._out.write(line.rstrip() + '\n')
                self._out.write('\n')

            # Display some information about the xapian version and platform
            self._out.write("Xapian version: %s\n" % _xapian.version_string())
            try:
                import platform
                platdesc = "%s %s (%s)" % platform.system_alias(
                    platform.system(), platform.release(), platform.version())
                self._out.write("Platform: %s\n" % platdesc)
            except:
                pass
            self._out.write(
                '\nWhen reporting this problem, please quote all the preceding lines from\n"%s" onwards.\n\n'
                % firstline)

        self._out.flush()
Пример #16
0
def get_system() -> List:
    """
    Detect Linux platform. Not used at this stage.
    It is meant to enable password encryption in distros
    that can handle this well.
    """
    system = platform.system_alias(platform.system(), platform.release(),
                                   platform.version())
    return [system, detect_desktop_environment()]
Пример #17
0
    def test_sysinfo_defaults(self):
        config = Configuration()

        self.assertEqual(platform.machine(), config['machine'])
        self.assertEqual(platform.processor(), config['processor'])
        system, release, version = platform.system_alias(
            platform.system(), platform.release(), platform.version())
        self.assertEqual(system, config['os'])
        self.assertEqual(os.name, config['family'])
        self.assertEqual(release, config['version'])
Пример #18
0
def detect_os():
	global illegal_chars
	from platform import system,release,version,system_alias
	os_name = system_alias(system(),release(),version())[0].lower()
	if os_name=="windows":
		illegal_chars = [':','*','?','"','<','>','|']
	elif os_name=="linux":
		illegal_chars = []
	if format_symbol in illegal_chars:
		illegal_chars.remove(format_symbol)
	def GetSystemInformation(self):
		LogManager.Log.warning("Reading system information about CPUs")
		results = dict()
		results['Processor'] = platform.processor()
		results['ProcessorType'] = platform.machine()
		results['OS'] = platform.system()
		results['OSRelease'] = platform.release()
		results['OSVersion'] = platform.version()
		results['OSAlias'] = platform.system_alias(results['OS'], results['OSVersion'], results['OSVersion'])
		return results
Пример #20
0
def getCharsetId():
    (system, release, version) = platform.system_alias(platform.system(), platform.release(), platform.version())
    data = re.split("_|\.|@?", locale.setlocale(locale.LC_ALL, ''))
    data[2] = data[2].replace("_", "-").upper()
    if data[2] in CHARSETS:
        return CHARSETS[data[2]]
    elif (re.match("windows", system, re.I) is not None
          or re.match("windows", release, re.I) is not None) and "MS" + data[2] in CHARSETS:
        return CHARSETS["MS" + data[2]]
    else:
        return 0
Пример #21
0
 def platform_id(self):
     try:
         import platform
         x = platform.uname()
         return platform.system_alias(x[0], x[2], x[3])
     except (ImportError, AttributeError):
         try:
             x = os.uname()
             return (x[0], x[2], x[3])
         except AttributeError:
             return (sys.platform, "unknown", "unknown")
Пример #22
0
def get_python_os_info(pretty: bool = False) -> Tuple[str, str]:
    """
    Get Operating System type/distribution and major version
    using python platform module

    :param bool pretty: If the returned OS name should be in longer (pretty) form

    :returns: (os_name, os_version)
    :rtype: `tuple` of `str`
    """
    info = platform.system_alias(platform.system(), platform.release(),
                                 platform.version())
    os_type, os_ver, _ = info
    os_type = os_type.lower()
    if os_type.startswith('linux') and _USE_DISTRO:
        distro_name, distro_version = distro.name() if pretty else distro.id(
        ), distro.version()
        # On arch, these values are reportedly empty strings so handle it
        # defensively
        # so handle it defensively
        if distro_name:
            os_type = distro_name
        if distro_version:
            os_ver = distro_version
    elif os_type.startswith('darwin'):
        try:
            proc = subprocess.run(
                ["/usr/bin/sw_vers", "-productVersion"],
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE,
                check=False,
                universal_newlines=True,
                env=env_no_snap_for_external_calls(),
            )
        except OSError:
            proc = subprocess.run(
                ["sw_vers", "-productVersion"],
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE,
                check=False,
                universal_newlines=True,
                env=env_no_snap_for_external_calls(),
            )
        os_ver = proc.stdout.rstrip('\n')
    elif os_type.startswith('freebsd'):
        # eg "9.3-RC3-p1"
        os_ver = os_ver.partition("-")[0]
        os_ver = os_ver.partition(".")[0]
    elif platform.win32_ver()[1]:
        os_ver = platform.win32_ver()[1]
    else:
        # Cases known to fall here: Cygwin python
        os_ver = ''
    return os_type, os_ver
Пример #23
0
def get_charset_id():
    (system, release, version) = platform.system_alias(platform.system(), platform.release(), platform.version())
    data = re.split("_|\.|@?", locale.setlocale(locale.LC_ALL, ''))
    data[2] = data[2].replace("_", "-").upper()
    data[2] = data[2].replace("UTF8", "UTF-8")
    if data[2] in CHARSETS:
        return CHARSETS[data[2]]
    if (re.match("windows", system, re.I)
        or re.match("windows", release, re.I)) and "MS" + data[2] in CHARSETS:
        return CHARSETS["MS" + data[2]]
    return 0
Пример #24
0
    def test_sysinfo_defaults(self):
        config = Configuration()

        self.assertEqual(platform.machine(), config['machine'])
        self.assertEqual(platform.processor(), config['processor'])
        system, release, version = platform.system_alias(platform.system(),
                                                         platform.release(),
                                                         platform.version())
        self.assertEqual(system, config['os'])
        self.assertEqual(os.name, config['family'])
        self.assertEqual(release, config['version'])
 def GetSystemInformation(self):
     LogManager.Log.warning("Reading system information about CPUs")
     results = dict()
     results['Processor'] = platform.processor()
     results['ProcessorType'] = platform.machine()
     results['OS'] = platform.system()
     results['OSRelease'] = platform.release()
     results['OSVersion'] = platform.version()
     results['OSAlias'] = platform.system_alias(results['OS'],
                                                results['OSVersion'],
                                                results['OSVersion'])
     return results
Пример #26
0
def detect_os():
	global illegal_chars,correct_filename
	from platform import system,release,version,system_alias
	os_name = system_alias(system(),release(),version())[0].lower()
	if os_name=="windows":
		illegal_chars = [':','*','?','"','<','>','|','\0']
		current_format.set_correct_filename(correct_filename)
	elif os_name=="linux":
		illegal_chars = ['\0']
		current_format.set_correct_filename(lambda string : string)
	if Format.symbol in illegal_chars:
		illegal_chars.remove(Format.symbol)
Пример #27
0
def run_debug_gui(logpath):
    import time, platform
    time.sleep(3)  # Give previous GUI time to shutdown fully and release locks
    from calibre.constants import __appname__, __version__, isosx
    print __appname__, _('Debug log')
    print __appname__, __version__
    print platform.platform()
    print platform.system()
    print platform.system_alias(platform.system(), platform.release(),
                                platform.version())
    print 'Python', platform.python_version()
    try:
        if iswindows:
            print 'Windows:', platform.win32_ver()
        elif isosx:
            print 'OSX:', platform.mac_ver()
        else:
            print 'Linux:', platform.linux_distribution()
    except:
        pass
    from calibre.gui2.main import main
    main(['__CALIBRE_GUI_DEBUG__', logpath])
Пример #28
0
def get_platform_id():
    (system, release, version) = platform.system_alias(platform.system(), platform.release(), platform.version())
    if re.match("windows", system, re.I) or re.match("windows", release, re.I):
        return PLATFORMS['MS_WINDOWS']
    if re.match("solaris", system, re.I) or re.match("solaris", release, re.I):
        return PLATFORMS['SOLARIS']
    if re.match("aix", system, re.I) or re.match("aix", release, re.I):
        return PLATFORMS['AIX']
    if re.match("hpux", system, re.I) or re.match("hpux", release, re.I):
        return PLATFORMS['HP_UX']
    if re.match("linux", system, re.I) or re.match("linux", release, re.I):
        return PLATFORMS['LINUX']
    return 0
Пример #29
0
def systemInfo():
    '''
    Returns a tuple containing the following information:
    - system name (e.g. Darwin, Windows, Ubuntu etc.)
    - release (e.g.: 12.04 for Ubuntu, 11.4.0 for Darwin etc.)
    - version
    The difference between platform.system_alias() and this function is that
    this function returns the Linux distribution name and version instead of
    'Linux' and the kernel version.
    '''
    sys, rel, ver = system_alias(system(), release(), version())
    if sys == 'Linux':
        sys, rel, _relname = linux_distribution()
    return (sys, rel, ver)
Пример #30
0
def mininginfo():
  file_info = os.stat(fpath)
  print "file_info:",file_info
  last_modified = file_info.st_mtime
  dt = datetime.datetime.fromtimestamp(last_modified)
  print "last_modified_time:",dt.strftime("%Y-%m-%d %H:%M:%S")  # Print最終更新日時

  #OS等paltform情報を読み取る(PC固有情報になるのか?)
  #参考?:http://docs.python.jp/2.6/library/platform.html
  print 'machine:',
  print platform.machine()
  print platform.node()
  print platform.platform(0,0)
  print platform.processor()
  print platform.python_build()
  sys_info =platform.system()
  sys_re = platform.release()
  sys_ver = platform.version()
  print sys_info,sys_re,sys_ver
  print platform.system_alias(sys_info, sys_re, sys_ver)
  print platform.uname()

  print os.getpid()
Пример #31
0
def get_python_os_info(pretty=False):
    """
    Get Operating System type/distribution and major version
    using python platform module

    :param bool pretty: If the returned OS name should be in longer (pretty) form

    :returns: (os_name, os_version)
    :rtype: `tuple` of `str`
    """
    info = platform.system_alias(platform.system(), platform.release(),
                                 platform.version())
    os_type, os_ver, _ = info
    os_type = os_type.lower()
    if os_type.startswith('linux') and _USE_DISTRO:
        info = distro.linux_distribution(pretty)
        # On arch, distro.linux_distribution() is reportedly ('','',''),
        # so handle it defensively
        if info[0]:
            os_type = info[0]
        if info[1]:
            os_ver = info[1]
    elif os_type.startswith('darwin'):
        try:
            proc = subprocess.Popen(
                ["/usr/bin/sw_vers", "-productVersion"],
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE,
                universal_newlines=True,
                env=env_no_snap_for_external_calls(),
            )
        except OSError:
            proc = subprocess.Popen(
                ["sw_vers", "-productVersion"],
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE,
                universal_newlines=True,
                env=env_no_snap_for_external_calls(),
            )
        os_ver = proc.communicate()[0].rstrip('\n')
    elif os_type.startswith('freebsd'):
        # eg "9.3-RC3-p1"
        os_ver = os_ver.partition("-")[0]
        os_ver = os_ver.partition(".")[0]
    elif platform.win32_ver()[1]:
        os_ver = platform.win32_ver()[1]
    else:
        # Cases known to fall here: Cygwin python
        os_ver = ''
    return os_type, os_ver
Пример #32
0
def systemInfo():
    '''
    Returns a tuple containing the following information:
    - system name (e.g. Darwin, Windows, Ubuntu etc.)
    - release (e.g.: 12.04 for Ubuntu, 11.4.0 for Darwin etc.)
    - version
    The difference between platform.system_alias() and this function is that
    this function returns the Linux distribution name and version instead of
    'Linux' and the kernel version.
    '''
    sys, rel, ver = system_alias(system(), release(), version())
    if sys == 'Linux':
        sys, rel, _relname = linux_distribution()
    return (sys, rel, ver)
Пример #33
0
def getPlatformId():
    (system, release, version) = platform.system_alias(platform.system(), platform.release(), platform.version())
    if re.match("windows", system, re.I) is not None or re.match("windows", release, re.I) is not None:
        return PLATFORMS['MS_WINDOWS']
    elif re.match("solaris", system, re.I) is not None or re.match("solaris", release, re.I) is not None:
        return PLATFORMS['SOLARIS']
    elif re.match("aix", system, re.I) is not None or re.match("aix", release, re.I) is not None:
        return PLATFORMS['AIX']
    elif re.match("hpux", system, re.I) is not None or re.match("hpux", release, re.I) is not None:
        return PLATFORMS['HP_UX']
    elif re.match("linux", system, re.I) is not None or re.match("linux", release, re.I) is not None:
        return PLATFORMS['LINUX']
    else:
        return 0
    def __init__(self):
        '''
        Initialize the class. Return standard runtime environment.
        '''

        self.theArchitecture = platform.architecture(executable=sys.executable,
                                                     bits='',
                                                     linkage='')
        self.theMachine = platform.machine()
        self.theNode = platform.node()

        if platformAvailable:
            # Introduced with Python 2.3
            self.thePlatform = platform.platform(aliased=1, terse=0)
        else:
            # NOT Introduced until Python 2.3
            self.thePlatform = ''

        if platformAvailable:
            try:
                # Introduced with Python 2.6
                self.thePython_branch = platform.python_branch()
                self.thePython_implementation = \
                                              platform.python_implementation()
                self.thePython_revision = platform.python_revision()
            except Exception as errorCode:
                # NOT Introduced until Python 2.6
                self.thePython_branch = ''
                self.thePython_implementation = ''
                self.thePython_revision = ''
        else:
            # NOT Introduced until Python 2.6
            self.thePython_branch = ''
            self.thePython_implementation = ''
            self.thePython_revision = ''

        self.theProcessor = platform.processor()
        self.thePython_build = platform.python_build()
        self.thePython_compiler = platform.python_compiler()
        self.thePython_version = platform.python_version()
        self.thePython_version_tuple = platform.python_version_tuple()
        self.theRelease = platform.release()
        self.theSystem = platform.system()
        self.theUname = platform.uname()
        self.theVersion = platform.version()

        self.theSystem_alias = platform.system_alias(self.theSystem,
                                                     self.theRelease,
                                                     self.theVersion)
Пример #35
0
def run_debug_gui(logpath):
    import time, platform

    time.sleep(3)  # Give previous GUI time to shutdown fully and release locks
    from calibre.constants import __appname__, __version__, isosx

    print __appname__, _("Debug log")
    print __appname__, __version__
    print platform.platform()
    print platform.system()
    print platform.system_alias(platform.system(), platform.release(), platform.version())
    print "Python", platform.python_version()
    try:
        if iswindows:
            print "Windows:", platform.win32_ver()
        elif isosx:
            print "OSX:", platform.mac_ver()
        else:
            print "Linux:", platform.linux_distribution()
    except:
        pass
    from calibre.gui2.main import main

    main(["__CALIBRE_GUI_DEBUG__", logpath])
Пример #36
0
    def __init__(self):
        import platform
        system_alias_name = platform.system_alias(platform.system(),
                                                  platform.release(),
                                                  platform.version())[0] or _("Computer")
        Topic.__init__(self,
                       system_alias_name,
                       uri="topic://Computer",
                       icon="computer")

        from gimmie_running import ComputerRunningSource
        self.set_running_source_factory(lambda: ComputerRunningSource())

        self.update_time_timeout_id = None
        self.current_time = 0
Пример #37
0
def get_python_os_info():
    """
    Get Operating System type/distribution and major version
    using python platform module

    :returns: (os_name, os_version)
    :rtype: `tuple` of `str`
    """
    info = platform.system_alias(
        platform.system(),
        platform.release(),
        platform.version()
    )
    os_type, os_ver, _ = info
    os_type = os_type.lower()
    if os_type.startswith('linux'):
        info = platform.linux_distribution()
        # On arch, platform.linux_distribution() is reportedly ('','',''),
        # so handle it defensively
        if info[0]:
            os_type = info[0]
        if info[1]:
            os_ver = info[1]
    elif os_type.startswith('darwin'):
        try:
            proc = subprocess.Popen(
                ["/usr/bin/sw_vers", "-productVersion"],
                stdout=subprocess.PIPE,
                universal_newlines=True,
            )
        except OSError:
            proc = subprocess.Popen(
                ["sw_vers", "-productVersion"],
                stdout=subprocess.PIPE,
                universal_newlines=True,
            )
        os_ver = proc.communicate()[0].rstrip('\n')
    elif os_type.startswith('freebsd'):
        # eg "9.3-RC3-p1"
        os_ver = os_ver.partition("-")[0]
        os_ver = os_ver.partition(".")[0]
    elif platform.win32_ver()[1]:
        os_ver = platform.win32_ver()[1]
    else:
        # Cases known to fall here: Cygwin python
        os_ver = ''
    return os_type, os_ver
Пример #38
0
def SystemVersion():
    #from sys import platform as _platform
    import platform
    #import os
    from collections import namedtuple
    ver = namedtuple("ver", [
        "machine", "network_name", "processor_name", "python_compiler",
        "python_implementation", "python_version", "python_version_tuple",
        "system_release", "system_system", "system_version", "system_tuple",
        "system_uname", "platform_info"
    ])
    platform_information = ""
    try:  # Java Platform
        platform_information = platform.java_ver()
        if platform_information[0] == '':
            raise Exception()
    except:
        try:  # Windows Platform
            platform_information = platform.win32_ver()
            if platform_information[0] == '':
                raise Exception()
        except:
            try:  # Mac OS Platform
                platform_information = platform.mac_ver()
                if platform_information[0] == '':
                    raise Exception()
            except:  # Unknown
                platform_information = ()
    osversion = ver(machine=platform.machine(),
                    network_name=platform.node(),
                    processor_name=platform.processor(),
                    python_compiler=platform.python_compiler(),
                    python_implementation=platform.python_implementation(),
                    python_version=platform.python_version(),
                    python_version_tuple=platform.python_version_tuple(),
                    system_system=platform.system(),
                    system_release=platform.release(),
                    system_version=platform.version(),
                    system_tuple=platform.system_alias(platform.system(),
                                                       platform.release(),
                                                       platform.version()),
                    system_uname=platform.uname(),
                    platform_info=platform_information)
    return osversion
Пример #39
0
def system_identify():
    if build_os == 'Windows':
        release, version, csd, ptype = platform.win32_ver()
        plat_str = 'release {}, version {}, service pack {}, type {}'.format(
          release, version, csd, ptype)
    elif build_os == 'Linux':
        # Avoid the deprecated platform.dist().
        lib, version = platform.libc_ver()
        plat_str = '{} version {}'.format(lib, version)
    elif build_os == 'OS_X':
        release, (version, dev_stage, non_release_version), machine = \
          platform.mac_ver()
        plat_str = ('release {}, dev stage {}, non-relase version {}, machine '
          '{}'.format(release, version, dev_stage, non_release_version,
                      machine))
    system, release, version = platform.system_alias(platform.system(),
      platform.release(), platform.version())
    flush_print('Python {}, OS {}, platform {} {} - {}'.format(sys.version, os.name,
      system, release, version, plat_str))
Пример #40
0
 def update_attributes(self):
     system, release, version = platform.system_alias(platform.system(), platform.release(), platform.version())
     uptime=time.time() - self.creation_time
     uphours=int(uptime/3600)
     updays=int(uphours/24)
     uphours=uphours-updays*24
     uptime=f"{updays}d, {uphours}h"
     attributes={
         'System': system,
         'Release': release,
         'Version': version,
         'Host': socket.gethostname(),
         'MAC': self.mac_address,
         'IP': self.ip_address,
         'Sensor uptime': uptime,
         'Sensor version': HA_VERSION
     }
     attribs_payload=json.dumps(attributes)
     self.mqtt.publish(self.attributes_topic, attribs_payload)
Пример #41
0
def print_basic_debug_info(out=None):
    if out is None: out = sys.stdout
    out = functools.partial(prints, file=out)
    import platform
    from calibre.constants import __appname__, get_version, isportable, isosx
    out(__appname__, get_version(), 'Portable' if isportable else '')
    out(platform.platform(), platform.system())
    out(platform.system_alias(platform.system(), platform.release(),
            platform.version()))
    out('Python', platform.python_version())
    try:
        if iswindows:
            out('Windows:', platform.win32_ver())
        elif isosx:
            out('OSX:', platform.mac_ver())
        else:
            out('Linux:', platform.linux_distribution())
    except:
        pass
Пример #42
0
def runBenchmarks(infilename,outfilename,sample_count,timeout,memout,product,buildenv,number_workers = cpu_count()):
    import platform    
    runenv = { "os" : " ".join(platform.system_alias(platform.system(),platform.release(),platform.version())),
               "arch" : platform.machine(),
               "processor" : platform.processor() }

    bf = BenchmarkFile(infilename)
    
    runqueue = RunQueue(number_workers)
    for b in bf.benchmarks:
        endTaskHandler = EndTaskHandler(b,runqueue,sample_count)
        for i in range(0,sample_count):
            runqueue.add(b,endTaskHandler,maxtime=timeout,maxmem=memout)
        
    runqueue.wait()    

    f = open(outfilename,"w")
    f.write(getBenchmarksXML(bf,product,buildenv,runenv))
    f.close()
Пример #43
0
def print_basic_debug_info(out=None):
    if out is None:
        out = sys.stdout
    out = functools.partial(prints, file=out)
    import platform
    from calibre.constants import __appname__, get_version, isportable, isosx, isfrozen, is64bit

    out(__appname__, get_version(), "Portable" if isportable else "", "isfrozen:", isfrozen, "is64bit:", is64bit)
    out(platform.platform(), platform.system(), platform.architecture())
    out(platform.system_alias(platform.system(), platform.release(), platform.version()))
    out("Python", platform.python_version())
    try:
        if iswindows:
            out("Windows:", platform.win32_ver())
        elif isosx:
            out("OSX:", platform.mac_ver())
        else:
            out("Linux:", platform.linux_distribution())
    except:
        pass
Пример #44
0
def system_identify():
    if build_os == 'Windows':
        release, version, csd, ptype = platform.win32_ver()
        plat_str = 'release {}, version {}, service pack {}, type {}'.format(
            release, version, csd, ptype)
    elif build_os == 'Linux':
        # Avoid the deprecated platform.dist().
        lib, version = platform.libc_ver()
        plat_str = '{} version {}'.format(lib, version)
    elif build_os == 'OS_X':
        release, (version, dev_stage, non_release_version), machine = \
          platform.mac_ver()
        plat_str = ('release {}, dev stage {}, non-relase version {}, machine '
                    '{}'.format(release, version, dev_stage,
                                non_release_version, machine))
    system, release, version = platform.system_alias(platform.system(),
                                                     platform.release(),
                                                     platform.version())
    flush_print('Python {}, OS {}, platform {} {} - {}'.format(
        sys.version, os.name, system, release, version, plat_str))
Пример #45
0
 def do_printenv(cls, line):
     """
     Print information about the runtime environment.
     Run in the shell with:  printenv
     """
     logger = logging.getLogger(__name__)
     if line is None:  # Put this here to get rid of PyCharm warning about line not being used
         pass
     print("Python version (sys.version) = " + sys.version)
     # Print value of environment variables that impact Python, alphabetized.
     # - skip the more esoteric ones
     # - See:  https://docs.python.org/2/using/cmdline.html
     env_vars = [
         "PYTHONBYTECODE", "PYTHONDEBUG", "PYTHONHOME", "PYTHONHTTPSVERIFY",
         "PYTHONOPTIMIZE", "PYTHONPATH", "PYTHONSTARTUP", "PYTHONUSERBASE",
         "PYTHONUSERSITE", "PYTHONVERBOSE"
     ]
     for env_var in env_vars:
         try:
             print(env_var + " = " + os.environ[env_var])
         except KeyError:
             print(env_var + " = not defined")
     print("os.getcwd() = " + os.getcwd())
     print("platform.architecture = " + str(platform.architecture()))
     print("platform.machine = " + platform.machine())
     print("platform.node = " + platform.node())
     print("platform.platform = " + platform.platform())
     print("platform.processor = " + platform.processor())
     print("platform.system = " + platform.system())
     print("platform.system_alias = " + str(
         platform.system_alias(platform.system(), platform.release(),
                               platform.version())))
     print("user = "******"GeoProcessor properties:")
     for property_name, property_value in processor.properties.items():
         print(property_name + " = " + str(property_value))
Пример #46
0
    def test_sysinfo_configfile_partial_override(self):
        inifd, ininame = tempfile.mkstemp(prefix='bitten_test')
        try:
            os.write(inifd, """
[machine]
name = MACHINE

[os]
name = OS
""")
            os.close(inifd)
            config = Configuration(ininame)

            self.assertEqual('MACHINE', config['machine'])
            self.assertEqual('OS', config['os'])
            # Remaining options should be set to default value
            system, release, version = platform.system_alias(
                platform.system(), platform.release(), platform.version())
            self.assertEqual(platform.processor(), config['processor'])
            self.assertEqual(os.name, config['family'])
            self.assertEqual(release, config['version'])
        finally:
            os.remove(ininame)
Пример #47
0
 def __init__(self, url, logging_object, language_object):
     """
     This is the __init__ methode... Nothing more information needed.
     
     Variables:
         - url                    ``string``
             the url from which the data will be extracted from.
     """
     self.url = url
     self.logging_object = logging_object
     self.language_object = language_object
     self.webpage = ""
     self._get_webpage_()
     
     # the headers for the webrequest
     self._headers = {
         'User-agent': (("{AppName}/{Version}({Platform})"
                         "Python-urllib/{PythonBuild} from {Hosted}"
                         ).format(
                             AppName=gobjects.__AppName__,
                             Version=gobjects.__version__,
                             Platform=('; '.join(
                                             platform.system_alias(
                                                 platform.system(),
                                                 platform.release(),
                                                 platform.version()
                                                 )
                                                   )
                                         ),
                             PythonBuild=platform.python_build(),
                             Hosted=gobjects.__hosted__
                             )
                        ),
         "Content-Type":
             "application/x-www-form-urlencoded;charset=utf-8",
         "Accept-Encoding": "gzip,deflate"
     }
Пример #48
0
    def test_sysinfo_configfile_partial_override(self):
        inifd, ininame = tempfile.mkstemp(prefix='bitten_test')
        try:
            os.write(inifd, """
[machine]
name = MACHINE

[os]
name = OS
""")
            os.close(inifd)
            config = Configuration(ininame)

            self.assertEqual('MACHINE', config['machine'])
            self.assertEqual('OS', config['os'])
            # Remaining options should be set to default value
            system, release, version = platform.system_alias(platform.system(),
                                                         platform.release(),
                                                         platform.version())
            self.assertEqual(platform.processor(), config['processor'])
            self.assertEqual(os.name, config['family'])
            self.assertEqual(release, config['version'])
        finally:
            os.remove(ininame)
Пример #49
0
 def test_system_alias(self):
     res = platform.system_alias(
         platform.system(),
         platform.release(),
         platform.version(),
     )
Пример #50
0
        ('version', '-'.join(platform.win32_ver()[1:3]))
    ])
elif sys.platform.startswith('java'):
    _name, _ver, _arch = platform.java_ver()[-1]
    _METADATA['os'] = SON([
        # Linux, Windows 7, Mac OS X, etc.
        ('type', _name),
        ('name', _name),
        # x86, x86_64, AMD64, etc.
        ('architecture', _arch),
        # Linux kernel version, OSX version, etc.
        ('version', _ver)
    ])
else:
    # Get potential alias (e.g. SunOS 5.11 becomes Solaris 2.11)
    _aliased = platform.system_alias(
        platform.system(), platform.release(), platform.version())
    _METADATA['os'] = SON([
        ('type', platform.system()),
        ('name', ' '.join([part for part in _aliased[:2] if part])),
        ('architecture', platform.machine()),
        ('version', _aliased[2])
    ])

if platform.python_implementation().startswith('PyPy'):
    _METADATA['platform'] = ' '.join(
        (platform.python_implementation(),
         '.'.join(imap(str, sys.pypy_version_info)),
         '(Python %s)' % '.'.join(imap(str, sys.version_info))))
elif sys.platform.startswith('java'):
    _METADATA['platform'] = ' '.join(
        (platform.python_implementation(),
Пример #51
0
def main():
	p = {}

	if platform.system() == 'Darwin': #osx
		try:
			#someday, the next line may be helpful for OSX
			p['os'] = platform.system_alias(platform.system(),platform.release(),platform.mac_ver())[0] or None
			p['type'] = 'Darwin'
			p['release'] = platform.mac_ver()[0] or None
			p['platform'] = platform.platform() or None
			p['python_version'] = platform.python_version() or None
			p['current_uid'] = pwd.getpwuid(os.getuid())[2]
			p['current_gid'] = pwd.getpwuid(os.getuid())[3]
			p['current_user'] = pwd.getpwuid(os.getuid())[0]
			p['current_user_group'] = grp.getgrgid(pwd.getpwnam(p['current_user']).pw_gid).gr_name
			p['current_user_desktop'] = os.path.join(os.path.expanduser('~'), 'Desktop')
			p['current_user_homedir'] = os.path.expanduser(('~'))
			p['tmp_dir'] = tempfile.gettempdir()
			#Dot is there as a hack until joining ~ and a dir does more than just give [1:]
			p['current_user_plist_dir'] = os.path.join(os.path.expanduser('~'),'./Library/LaunchAgents/')
		except IOError:
			return_error('Could not get more specific information for Darwin-based platform')
	elif platform.system() == 'Linux':
		try:
			p['os'] = platform.linux_distribution()[0] or None
			p['type'] = 'Linux'
			p['release'] = platform.linux_distribution()[1] or None
			p['platform'] = platform.platform() or None
			p['python_version'] = platform.python_version() or None
			p['current_uid'] = pwd.getpwuid(os.getuid())[2]
			p['current_gid'] = pwd.getpwuid(os.getuid())[3]
			p['current_user'] = pwd.getpwuid(os.getuid())[0]
			p['current_user_group'] = grp.getgrgid(pwd.getpwnam(p['current_user']).pw_gid).gr_name
			p['current_user_desktop'] = subprocess.check_output(['xdg-user-dir', 'DESKTOP'])
			p['tmp_dir'] = tempfile.gettempdir()
		except:
			return_error('Could not get more specific information for Linux-based platform')
	elif platform.system() == 'Windows':
		try:
			p['os'] = "{0} {1}".format(platform.win32_ver()[0],platform.win32_ver()[2] or '') or None
			p['type'] = 'Windows'
			p['release'] = platform.win32_ver()[0] or None
			p['platform'] = platform.platform() or None
			p['python_version'] = platform.python_version() or None
			p['current_user_desktop'] = os.path.join(os.path.expanduser('~'), 'Desktop')
			#I don't know the Windows equiv of getting UID/GID.. last I checked, it was terrible and I don't
			#really care that much about Windows as long as Microsoft makes simple things annoying.
			p['tmp_dir'] = tempfile.gettempdir()
		except:
			return_error('Could not get more specific information for Windows-based platform')
	else:
		try:
			p['os'] = platform.linux_distribution()[0] or None
			p['type'] = 'unknown'
			p['release'] = platform.linux_distribution()[1] or None
			p['platform'] = platform.platform() or None
			p['python_version'] = platform.python_version() or None
			p['tmp_dir'] = tempfile.gettempdir() or None
			p['current_uid'] = p['current_gid'] = None
			p['current_user'] = p['current_user_group'] = p['current_user_desktop'] = None
		except:
			return_error('Could not get platform information.')

	return p
Пример #52
0
    def load_machine_vars(self, machine_var_data_manager: DataManager,
                          current_time) -> None:
        """Load machine vars from data manager."""
        self.machine_var_data_manager = machine_var_data_manager

        for name, settings in (iter(
                self.machine_var_data_manager.get_data().items())):

            if not isinstance(settings, dict) or "value" not in settings:
                continue

            if ('expire' in settings and settings['expire']
                    and settings['expire'] < current_time):

                continue

            self.set_machine_var(name=name, value=settings['value'])

        self._load_initial_machine_vars()

        # Create basic system information machine variables
        self.set_machine_var(name="mpf_version", value=mpf_version)
        '''machine_var: mpf_version

        desc: Full version string for MPF.
        '''
        self.set_machine_var(name="mpf_extended_version",
                             value=mpf_extended_version)
        '''machine_var: mpf_extended_version

        desc: Extended version string for MPF. Contains show and bcp version as well.
        '''
        self.set_machine_var(name="python_version", value=python_version())
        '''machine_var: python_version

        desc: Python version.
        '''
        self.set_machine_var(name="platform", value=platform(aliased=True))
        '''machine_var: platform

        desc: A single string identifying the underlying platform
              with as much useful information as possible.
        '''
        platform_info = system_alias(system(), release(), version())
        self.set_machine_var(name="platform_system", value=platform_info[0])
        '''machine_var: platform_system

        desc: Your system (Linux/Windows/Mac).
        '''
        self.set_machine_var(name="platform_release", value=platform_info[1])
        '''machine_var: platform_release

        desc: Release of your operating system.
        '''
        self.set_machine_var(name="platform_version", value=platform_info[2])
        '''machine_var: platform_version

        desc: Version of your operating system.
        '''
        self.set_machine_var(name="platform_machine", value=platform_machine())
        '''machine_var: platform_machine
Пример #53
0
 def test_system_alias(self):
     res = platform.system_alias(
         platform.system(),
         platform.release(),
         platform.version(),
     )
Пример #54
0
    platforminfo['machine'] = platform.machine()
    platforminfo['node'] = platform.node()
    platforminfo['platform'] = platform.platform(aliased=0, terse=0)
    platforminfo['processor'] = platform.processor()
    platforminfo['architecture'] = platform.architecture()
    platforminfo['python_build'] = platform.python_build()
    platforminfo['python_version'] = platform.python_version()
    platforminfo['python_compiler'] = platform.python_compiler()
    platforminfo['python_branch'] = platform.python_branch()
    platforminfo['python_implementation'] = platform.python_implementation()
    platforminfo['python_revision'] = platform.python_revision()
    platforminfo['python_version_tuple'] = platform.python_version_tuple()
    platforminfo['release'] = platform.release()
    platforminfo['system'] = platform.system()
    platforminfo['version'] = platform.version()
    platforminfo['system_alias'] = platform.system_alias(
        platforminfo['system'], platforminfo['release'],
        platforminfo['version'])
    platforminfo['uname'] = platform.uname()
    platforminfo['linux_distribution'] = platform.linux_distribution()

    return render_to_response(
        "home.html", {
            'request': request,
            'osinfo': osinfo,
            'hostinfo': hostinfo,
            'envinfo': envinfo,
            'platforminfo': platforminfo
        })
Пример #55
0
# TODO probably should obey pep8
# TODO logging
# TODO test mode

import os
import sys
from platform import system, system_alias, release, version, linux_distribution

if sys.version_info < (2, 6):
    print "I require 2.6 or higher"
    sys.exit(1)

# Determine OS type so I can use specific dotfiles
#     think about how to set this variable

_os, release, version = system_alias(system(), release(), version())
if _os.lower() == 'linux':
    myos = 'linux'
elif _os.lower() == 'darwin':
    myos = 'osx'
elif _os.lower() == 'win32':
    myos = 'windows'
else:
    # i dunno you should check this first
    print "I'm not sure what OS you're running, lets quit."
    sys.exit(1)

HOMEDIR = os.path.expanduser('~')
DIR = '%s/.dotfiles' % HOMEDIR
OLDDIR = '%s/.dotfiles_old' % HOMEDIR
SECRETS = 'url of secret repo'  # TODO set this, obv
Пример #56
0
def env():
    """ Returns a simple to use dictionary of common operating system details"""


    p = {}
    p['platform'] = platform.platform() or None
    p['python_version'] = platform.python_version() or None
    try:
        p['python_major_version'] =  p['python_version'][0]
    except TypeError:
        p['python_major_version'] = None
    p['python_version_feature_branch'] = '.'.join(platform.python_version().split('.')[0:2]) or None
    p['python_installed_packages'] = ["%s==%s" % (pkg.key, pkg.version) for pkg in pip.get_installed_distributions()]
    p['homedir'] = os.path.join(os.path.expanduser('~'))
    p['current_user_desktop'] = os.path.join(p['homedir'], 'Desktop') or None
    p['tmp_dir'] = tempfile.gettempdir()

    # Might fail on Windows.  Open a PR or issue on github if this is important to you.
    # This should probably get cleaned up by separating the getgrpid from getpwuid, but AFAIK, it's pass/fail
    try:
        pwuid = pwd.getpwuid(os.getuid())
        p['current_uid'] = pwuid[2]
        p['current_gid'] = pwuid[3]
        p['current_user'] = pwuid[0]
        p['current_user_group'] = grp.getgrgid(pwd.getpwnam(p['current_user']).pw_gid).gr_name
    except NameError:
        try:
            p['current_user'] = getpass.getuser()
        except AttributeError:
            # User is on some unknown OS
            p['current_user'] = None
        finally:
            p['current_uid'] = p['current_gid'] = p['current_user_group'] = None

    # Start OS-specific calls.
    if platform.system() == 'Darwin':
        try:
            p['type'] = 'Darwin'
            p['os'] = platform.system_alias(platform.system(), platform.release(), platform.mac_ver())[0] or None
            p['release'] = platform.mac_ver()[0] or None
        except Exception as e:
            raise Exception('Fatal error retrieving OS details on OSX: {}'.format(e))

    elif platform.system() == 'Linux':
        try:
            dist_info = platform.linux_distribution()
            p['type'] = 'Linux'
            p['os'] = dist_info[0] or None
            p['release'] = dist_info[1] or None
        except Exception as e:
            raise Exception('Fatal error retrieving OS details on Linux: {}'.format(e))

    elif platform.system() == 'Windows':
        try:
            p['type'] = 'Windows'
            p['os'] = str(platform.system() + platform.release()) or None
            p['release'] = platform.win32_ver()[0] or None
        except Exception as e:
            raise Exception('Fatal error retrieving OS details on Windows: {}'.format(e))

    else:
        # unknown OS. likely odd/new variant of linux/unix or windows
        # linx/unix is more important, so we default to that:
        try:
            dist_info = platform.linux_distribution()
            p['os'] = dist_info[0] or None
            p['type'] = 'unknown'
            p['release'] = dist_info[1] or None
        except Exception as e:
            raise NotImplementedError('Could not get platform information for unknown OS: {}'.format(e))

    return p
Пример #57
0
#!/usr/bin/env python
# encoding: utf-8
"""
这个文件中记录了所有的全局静态配置变量。现在只有named.conf所属路径和nameddb目录存储路径。
"""

import re
import os
import platform
import pwd
import sys
import errno

system, _, release, version, machine, processor = platform.uname()
system, release, version = platform.system_alias(system, release, version)
release = re.compile(r"^\d+.\d+").search(release).group()

# 安装路径,是否能传进来?暂时写成根据相对路径
installdir = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
# 这里记录了bind启动的chroot根目录
chroot_path = "/var/named"
# 这里记录了named.conf所存储的路径
namedconf = "/etc/namedb"
# 这是bind的启动脚本
namedstart = "/etc/rc.d/named start"
# 这是bind的停止脚本
namedstop = "/etc/rc.d/named stop"
# 这是bind的重启脚本
namedrestart = "/etc/rc.d/named restart"

if (system == 'Darwin'):
Пример #58
0
def print_current_platform():
    (system, node, release, version, machine, processor) = uname()
    bits = architecture()[0]
    alias = "%s %s %s" % system_alias(system, release, version)
    python = "%s %s" % (python_implementation(), python_version())
    print "Using %s (%s) on %s, %s" % (python, bits, alias, machine)