Python platform 模块,win32_ver() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用platform.win32_ver()

项目:stegator    作者:1modm    | 项目源码 | 文件源码
def build(self):
        if (any(platform.win32_ver())):
            stroutput = self.remove_accents(self.output)
        else:
            stroutput = self.output

        cmd = {'sender': self.sender,
                'receiver': self.receiver,
                'output': stroutput,
                'cmd': self.cmd,
                'jobid': self.jobid}
        return base64.b64encode(json.dumps(cmd))


#------------------------------------------------------------------------------
# Class ChromePasswords
#------------------------------------------------------------------------------
项目:FYP-AutoTextSum    作者:MrRexZ    | 项目源码 | 文件源码
def __convert_csv_to_coocur_dict(self, res_folder):
        import csv, win32api
        import platform
        cooccurrence_counts = defaultdict(float)
        new_words = []
        res_folder_gen = [label_folder for label_folder in os.listdir(res_folder) if label_folder[:2] != SUCCESS_HEADER]
        for label_folder in res_folder_gen:
            csv_gen = [csv_fname for csv_fname in os.listdir(os.path.join(res_folder, label_folder)) if csv_fname[-3:] == 'csv']
            for csv_fname in csv_gen:
                if any(platform.win32_ver()):
                    csv_file =  win32api.GetShortPathName(os.path.join(win32api.GetShortPathName(res_folder), label_folder, csv_fname))
                else:
                    csv_file = os.path.join(res_folder, label_folder, csv_fname)
                reader = csv.DictReader(open(csv_file), fieldnames=['tgt_word', 'ctx_word', 'coor_val'])
                for row in reader:
                    target_word = row['tgt_word']
                    context_word = row['ctx_word']
                    print(row['tgt_word'])
                    if (self.__embeddings is None or target_word not in self.__embeddings.keys()) and target_word not in new_words:
                        new_words.append(target_word)
                    if (self.__embeddings is None or context_word not in self.__embeddings.keys()) and context_word not in new_words:
                        new_words.append(context_word)
                    cooccurrence_counts[(target_word, context_word)] = row['coor_val']
        self.__new_words = new_words
        return cooccurrence_counts
项目:constructor    作者:conda    | 项目源码 | 文件源码
def system_info():
    import constructor, sys, platform
    import conda.exports, conda.config
    out = {'constructor': constructor.__version__,
           'conda': conda.__version__,
           'platform': sys.platform,
           'python': sys.version,
           'python_version': tuple(sys.version_info),
           'machine': platform.machine(),
           'platform_full': platform.version()}
    if sys.platform == 'darwin':
        out['extra'] = platform.mac_ver()
    elif sys.platform.startswith('linux'):
        out['extra'] = platform.dist()
    elif sys.platform.startswith('win'):
        out['extra'] = platform.win32_ver()
        prefix = os.environ.get('CONDA_PREFIX', conda.config.default_prefix)
        prefix_records = conda.exports.linked_data(prefix).values()
        nsis_prefix_rec = next(
            (rec for rec in prefix_records if rec.name == 'nsis'), None)
        if nsis_prefix_rec:
            out['nsis'] = nsis_prefix_rec.version
    return out
项目:FightstickDisplay    作者:calexil    | 项目源码 | 文件源码
def run(self):
        '''Begin processing events, scheduled functions and window updates.

        This method returns when `has_exit` is set to True.

        Developers are discouraged from overriding this method, as the
        implementation is platform-specific.
        '''
        self.has_exit = False
        self._legacy_setup()

        platform_event_loop = app.platform_event_loop
        platform_event_loop.start()
        self.dispatch_event('on_enter')

        self.is_running = True
        if compat_platform == 'win32' and int(platform.win32_ver()[0]) <= 5:
            self._run_estimated()
        else:
            self._run()
        self.is_running = False

        self.dispatch_event('on_exit')
        platform_event_loop.stop()
项目:cryptogram    作者:xinmingzhang    | 项目源码 | 文件源码
def run(self):
        '''Begin processing events, scheduled functions and window updates.

        This method returns when `has_exit` is set to True.

        Developers are discouraged from overriding this method, as the
        implementation is platform-specific.
        '''
        self.has_exit = False
        self._legacy_setup()

        platform_event_loop = app.platform_event_loop
        platform_event_loop.start()
        self.dispatch_event('on_enter')

        self.is_running = True
        if compat_platform == 'win32' and int(platform.win32_ver()[0]) <= 5:
            self._run_estimated()
        else:
            self._run()
        self.is_running = False

        self.dispatch_event('on_exit')
        platform_event_loop.stop()
项目:ZLib    作者:zenist    | 项目源码 | 文件源码
def __register_font(self):
        '''
        ????????,?????????????
        :return:
        '''
        if platform.system() == 'Windows':
            if platform.win32_ver()[0] == '8':
                __platform = 'Win8'
            else:
                __platform =  'Win7orLower'
        elif platform.system() == 'Linux':
            __platform =  'Linux'
        else:
            __platform =  'MacOS'

        if __platform != 'Win7orLower':
            if __platform == 'Win8':
                pdfmetrics.registerFont(TTFont('chsFont','msyh.TTC'))
            elif __platform == 'MacOS':
                pdfmetrics.registerFont(TTFont('chsFont', 'STHeiti Light.ttc'))
            elif __platform == 'Linux': #???linux??????????????????
                pdfmetrics.registerFont(TTFont('chsFont','STHeiti Light.ttc'))
        else:
            pdfmetrics.registerFont(TTFont('chsFont','msyh.TTF'))
项目:linuxacademy-dl    作者:vassim    | 项目源码 | 文件源码
def sys_info():
    result = {
        'platform': '{} [{}]'.format(platform.platform(), platform.version()),
        'python': '{} {}'.format(
            platform.python_implementation(),
            sys.version.replace('\n', '')
        ),
        'os': 'Unknown'
    }

    linux_ver = platform.linux_distribution()
    mac_ver = platform.mac_ver()
    win_ver = platform.win32_ver()

    if linux_ver[0]:
        result['os'] = 'Linux - {}'.format(' '.join(linux_ver))
    elif mac_ver[0]:
        result['os'] = 'OS X - {}'.format(' '.join(mac_ver[::2]))
    elif win_ver[0]:
        result['os'] = 'Windows - {}'.format(' '.join(win_ver[:2]))

    return result
项目:python-zulip-api    作者:zulip    | 项目源码 | 文件源码
def get_user_agent(self):
        # type: () -> str
        vendor = ''
        vendor_version = ''
        try:
            vendor = platform.system()
            vendor_version = platform.release()
        except IOError:
            # If the calling process is handling SIGCHLD, platform.system() can
            # fail with an IOError.  See http://bugs.python.org/issue9127
            pass

        if vendor == "Linux":
            vendor, vendor_version, dummy = platform.linux_distribution()
        elif vendor == "Windows":
            vendor_version = platform.win32_ver()[1]
        elif vendor == "Darwin":
            vendor_version = platform.mac_ver()[0]

        return "{client_name} ({vendor}; {vendor_version})".format(
            client_name=self.client_name,
            vendor=vendor,
            vendor_version=vendor_version,
        )
项目:NoWannaNoCry    作者:dolang    | 项目源码 | 文件源码
def os_id_index():
    """Get the index of the machine OS in the `OS_ID` tuple.

    The `OS_ID` tuple contains the major and minor version of all
    affected Windows versions.  These are matched against
    the major and minor version of `sys.getwindowsversion()`.

    For Windows 8.1 and above `sys.getwindowsversion()` doesn't
    report the correct value, these systems are handled specially. 

    Windows 8 and Server 2012 are special cased because the have the
    same version numbers but require different KBs.

    :return: The index of the operating system in `OS_ID`.
    :rtype: int
    """
    winver = sys.getwindowsversion()
    # sys.getwindowsversion is not enough by itself as the underlying
    # API has been deprecated.  Only applications which have been
    # developed specifically for Windows 8.1 and above, and write that
    # into their manifest file get the correct Windows version on those
    # systems.  Other applications (Python doesn't have the manifest)
    # get a version that pretends to be Windows 8 (major=6, minor=2).
    # See:
    # https://msdn.microsoft.com/en-us/library/windows/desktop/ms724834.aspx
    major, minor = winver.major, winver.minor
    if (major, minor) == (6, 2):
        # Determine if this system is a newer version than Windows 8 by
        # parsing the version string in `platform.win32_ver()[1]`:
        major, minor = tuple(map(int, platform.win32_ver()[1].split('.')[:2]))
    for i, os_id in enumerate(OS_ID):
        if os_id[:2] == (major, minor):
            if len(os_id) == 2:
                return i
            # else evaluate the third item if present which is a lambda:
            if os_id[2]():
                return i
            # otherwise continue with the next item
项目:aws-encryption-sdk-cli    作者:awslabs    | 项目源码 | 文件源码
def patch_platform_win32_ver(mocker):
    mocker.patch.object(arg_parsing.platform, 'win32_ver')
    return arg_parsing.platform.win32_ver
项目:aws-encryption-sdk-cli    作者:awslabs    | 项目源码 | 文件源码
def test_f_comment_ignoring_argument_parser_convert_filename():
    # Actually checks against the current local system
    parser = arg_parsing.CommentIgnoringArgumentParser()

    if any(platform.win32_ver()):
        assert not parser._CommentIgnoringArgumentParser__is_posix
        expected_transform = NON_POSIX_FILEPATH
    else:
        assert parser._CommentIgnoringArgumentParser__is_posix
        expected_transform = POSIX_FILEPATH

    parsed_line = [arg for arg in parser.convert_arg_line_to_args(expected_transform[0])]
    assert expected_transform[1] == parsed_line
项目:aws-encryption-sdk-cli    作者:awslabs    | 项目源码 | 文件源码
def is_windows():
    return any(platform.win32_ver())
项目:aws-encryption-sdk-cli    作者:awslabs    | 项目源码 | 文件源码
def is_windows():
    return any(platform.win32_ver())
项目:aws-encryption-sdk-cli    作者:awslabs    | 项目源码 | 文件源码
def __init__(self, *args, **kwargs):
        """Sets up the dummy argument registry."""
        # The type profile for this it really complex and we don't do anything to it, so
        # I would rather not duplicate the typeshed's effort keeping it up to date.
        # https://github.com/python/typeshed/blob/master/stdlib/2and3/argparse.pyi#L27-L39
        self.__dummy_arguments = []
        self.__is_posix = not any(platform.win32_ver())
        super(CommentIgnoringArgumentParser, self).__init__(*args, **kwargs)
项目:rfcat-firsttry    作者:atlas0fd00m    | 项目源码 | 文件源码
def getCurrentDef(normname):
    bname, wver, stuff, whichkern = platform.win32_ver()
    wvertup = wver.split('.')
    arch = envi.getCurrentArch()
    if isSysWow64():
        arch = 'wow64'

    modname = 'vstruct.defs.windows.win_%s_%s_%s.%s' % (wvertup[0], wvertup[1], arch, normname)

    try:
        mod = __import__(modname, {}, {}, 1)
    except ImportError, e:
        mod = None
    return mod
项目:zippy    作者:securesystemslab    | 项目源码 | 文件源码
def test_main(verbose=False):
    if support.verbose:
        plats = {
            'Linux': platform.linux_distribution,
            'Mac': platform.mac_ver,
            'Windows': platform.win32_ver,
        }
        for name, func in plats.items():
            plat = func()
            if plat and plat[0]:
                plat = '%s %r' % (name, plat)
                break
        else:
            plat = repr(platform.platform())
        print("test_ssl: testing with %r %r" %
            (ssl.OPENSSL_VERSION, ssl.OPENSSL_VERSION_INFO))
        print("          under %s" % plat)
        print("          HAS_SNI = %r" % ssl.HAS_SNI)

    for filename in [
        CERTFILE, SVN_PYTHON_ORG_ROOT_CERT, BYTES_CERTFILE,
        ONLYCERT, ONLYKEY, BYTES_ONLYCERT, BYTES_ONLYKEY,
        BADCERT, BADKEY, EMPTYCERT]:
        if not os.path.exists(filename):
            raise support.TestFailed("Can't read certificate file %r" % filename)

    tests = [ContextTests, BasicSocketTests]

    if support.is_resource_enabled('network'):
        tests.append(NetworkedTests)

    if _have_threads:
        thread_info = support.threading_setup()
        if thread_info and support.is_resource_enabled('network'):
            tests.append(ThreadedTests)

    try:
        support.run_unittest(*tests)
    finally:
        if _have_threads:
            support.threading_cleanup(*thread_info)
项目:zippy    作者:securesystemslab    | 项目源码 | 文件源码
def test_win32_ver(self):
        res = platform.win32_ver()
项目:python3-utils    作者:soldni    | 项目源码 | 文件源码
def is_windows():
    return any(platform.win32_ver())
项目:oil    作者:oilshell    | 项目源码 | 文件源码
def test_win32_ver(self):
        res = platform.win32_ver()
项目:oil    作者:oilshell    | 项目源码 | 文件源码
def genwincodec(codepage):
    import platform
    map = genwinmap(codepage)
    encodingname = 'cp%d' % codepage
    code = codegen("", map, encodingname)
    # Replace first lines with our own docstring
    code = '''\
"""Python Character Mapping Codec %s generated on Windows:
%s with the command:
  python Tools/unicode/genwincodec.py %s
"""#"
''' % (encodingname, ' '.join(platform.win32_ver()), codepage
      ) + code.split('"""#"', 1)[1]

    print code
项目:python2-tracer    作者:extremecoders-re    | 项目源码 | 文件源码
def test_win32_ver(self):
        res = platform.win32_ver()
项目:python2-tracer    作者:extremecoders-re    | 项目源码 | 文件源码
def genwincodec(codepage):
    import platform
    map = genwinmap(codepage)
    encodingname = 'cp%d' % codepage
    code = codegen("", map, encodingname)
    # Replace first lines with our own docstring
    code = '''\
"""Python Character Mapping Codec %s generated on Windows:
%s with the command:
  python Tools/unicode/genwincodec.py %s
"""#"
''' % (encodingname, ' '.join(platform.win32_ver()), codepage
      ) + code.split('"""#"', 1)[1]

    print code
项目:vivisect-py3    作者:bat-serjo    | 项目源码 | 文件源码
def getCurrentDef(normname):
    bname, wver, stuff, whichkern = platform.win32_ver()
    wvertup = wver.split('.')
    arch = envi.getCurrentArch()
    if isSysWow64():
        arch = 'wow64'

    modname = 'vstruct.defs.windows.win_%s_%s_%s.%s' % (wvertup[0], wvertup[1], arch, normname)

    try:
        mod = __import__(modname, {}, {}, 1)
    except ImportError as e:
        mod = None
    return mod
项目:web_ctp    作者:molebot    | 项目源码 | 文件源码
def test_main(verbose=False):
    if support.verbose:
        plats = {
            'Linux': platform.linux_distribution,
            'Mac': platform.mac_ver,
            'Windows': platform.win32_ver,
        }
        for name, func in plats.items():
            plat = func()
            if plat and plat[0]:
                plat = '%s %r' % (name, plat)
                break
        else:
            plat = repr(platform.platform())
        print("test_ssl: testing with %r %r" %
            (ssl.OPENSSL_VERSION, ssl.OPENSSL_VERSION_INFO))
        print("          under %s" % plat)
        print("          HAS_SNI = %r" % ssl.HAS_SNI)

    for filename in [
        CERTFILE, SVN_PYTHON_ORG_ROOT_CERT, BYTES_CERTFILE,
        ONLYCERT, ONLYKEY, BYTES_ONLYCERT, BYTES_ONLYKEY,
        BADCERT, BADKEY, EMPTYCERT]:
        if not os.path.exists(filename):
            raise support.TestFailed("Can't read certificate file %r" % filename)

    tests = [ContextTests, BasicSocketTests, SSLErrorTests]

    if support.is_resource_enabled('network'):
        tests.append(NetworkedTests)

    if _have_threads:
        thread_info = support.threading_setup()
        if thread_info:
            tests.append(ThreadedTests)

    try:
        support.run_unittest(*tests)
    finally:
        if _have_threads:
            support.threading_cleanup(*thread_info)
项目:web_ctp    作者:molebot    | 项目源码 | 文件源码
def test_win32_ver(self):
        res = platform.win32_ver()
项目:rfcat    作者:EnhancedRadioDevices    | 项目源码 | 文件源码
def getCurrentDef(normname):
    bname, wver, stuff, whichkern = platform.win32_ver()
    wvertup = wver.split('.')
    arch = envi.getCurrentArch()
    if isSysWow64():
        arch = 'wow64'

    modname = 'vstruct.defs.windows.win_%s_%s_%s.%s' % (wvertup[0], wvertup[1], arch, normname)

    try:
        mod = __import__(modname, {}, {}, 1)
    except ImportError, e:
        mod = None
    return mod
项目:rfcat    作者:atlas0fd00m    | 项目源码 | 文件源码
def getCurrentDef(normname):
    bname, wver, stuff, whichkern = platform.win32_ver()
    wvertup = wver.split('.')
    arch = envi.getCurrentArch()
    if isSysWow64():
        arch = 'wow64'

    modname = 'vstruct.defs.windows.win_%s_%s_%s.%s' % (wvertup[0], wvertup[1], arch, normname)

    try:
        mod = __import__(modname, {}, {}, 1)
    except ImportError, e:
        mod = None
    return mod
项目:ZLib    作者:zenist    | 项目源码 | 文件源码
def get_system_type(cls):
        '''???????????'''
        if platform.system() == 'Windows':
            if platform.win32_ver()[0] == '8':
                return 'Win8'
            else:
                return 'Win7orLower'
        elif platform.system() == 'Linux':
            return 'Linux'
        else:
            return 'MacOS'
项目:pefile.pypy    作者:cloudtracer    | 项目源码 | 文件源码
def test_win32_ver(self):
        res = platform.win32_ver()
项目:ouroboros    作者:pybee    | 项目源码 | 文件源码
def test_win32_ver(self):
        res = platform.win32_ver()
项目:ndk-python    作者:gittor    | 项目源码 | 文件源码
def test_win32_ver(self):
        res = platform.win32_ver()
项目:kbe_server    作者:xiaohaoppy    | 项目源码 | 文件源码
def test_win32_ver(self):
        res = platform.win32_ver()
项目:PandwaRF    作者:ComThings    | 项目源码 | 文件源码
def getCurrentDef(normname):
    bname, wver, stuff, whichkern = platform.win32_ver()
    wvertup = wver.split('.')
    arch = envi.getCurrentArch()
    if isSysWow64():
        arch = 'wow64'

    modname = 'vstruct.defs.windows.win_%s_%s_%s.%s' % (wvertup[0], wvertup[1], arch, normname)

    try:
        mod = __import__(modname, {}, {}, 1)
    except ImportError, e:
        mod = None
    return mod
项目:rvmi-rekall    作者:fireeye    | 项目源码 | 文件源码
def from_current_system(cls, session=None):
        """Gets a Uname object populated from the current system"""
        uname = platform.uname()
        fqdn = socket.getfqdn()
        system = uname[0]
        architecture, _ = platform.architecture()
        if system == "Windows":
            service_pack = platform.win32_ver()[2]
            kernel = uname[3]  # 5.1.2600
            release = uname[2]  # XP, 2000, 7
            version = uname[3] + service_pack  # 5.1.2600 SP3, 6.1.7601 SP1
        elif system == "Darwin":
            kernel = uname[2]  # 12.2.0
            release = "OSX"  # OSX
            version = platform.mac_ver()[0]  # 10.8.2
        elif system == "Linux":
            kernel = uname[2]  # 3.2.5
            release = platform.linux_distribution()[0]  # Ubuntu
            version = platform.linux_distribution()[1]  # 12.04

        # Emulate PEP 425 naming conventions - e.g. cp27-cp27mu-linux_x86_64.
        pep425tag = "%s%s-%s-%s" % (pep425tags.get_abbr_impl(),
                                    pep425tags.get_impl_ver(),
                                    str(pep425tags.get_abi_tag()).lower(),
                                    pep425tags.get_platform())

        return cls.from_keywords(
            session=session,
            system=system,
            architecture=architecture,
            node=uname[1],
            release=release,
            version=version,
            machine=uname[4],              # x86, x86_64
            kernel=kernel,
            fqdn=fqdn,
            pep425tag=pep425tag,
        )


# The rest will be automatically created as plain old data objects (PODO).
项目:toggl2shotgun    作者:jfboismenu    | 项目源码 | 文件源码
def _data_root_Windows():
    release, version, csd, ptype = platform.win32_ver()
    root = _settings_root_XP() if release == 'XP' else _settings_root_Vista()
    return os.path.join(root, 'Python Keyring')
项目:mrcrypt    作者:aol    | 项目源码 | 文件源码
def is_windows():
    return any(platform.win32_ver())
项目:DBAdapter    作者:ContinuumIO    | 项目源码 | 文件源码
def print_library_info(cnxn):
    from dbadapter import pyodbc
    import numpy as np
    print('python:  %s' % sys.version)
    print('pyodbc:  %s %s' % (pyodbc.version, os.path.abspath(pyodbc.__file__)))
    print('odbc:    %s' % cnxn.getinfo(pyodbc.SQL_ODBC_VER))
    print('numpy:   %s' % np.__version__)
    print('npodbc:  %s' % pyodbc.npversion)
    print('driver:  %s %s' % (cnxn.getinfo(pyodbc.SQL_DRIVER_NAME), cnxn.getinfo(pyodbc.SQL_DRIVER_VER)))
    print('         supports ODBC version %s' % cnxn.getinfo(pyodbc.SQL_DRIVER_ODBC_VER))
    print('os:      %s' % platform.system())
    print('unicode: Py_Unicode=%s SQLWCHAR=%s' % (pyodbc.UNICODE_SIZE, pyodbc.SQLWCHAR_SIZE))

    if platform.system() == 'Windows':
        print('         %s' % ' '.join([s for s in platform.win32_ver() if s]))
项目:DBAdapter    作者:ContinuumIO    | 项目源码 | 文件源码
def print_library_info(cnxn):
    import pyodbc
    print 'python:  %s' % sys.version
    print 'pyodbc:  %s %s' % (pyodbc.version, os.path.abspath(pyodbc.__file__))
    print 'odbc:    %s' % cnxn.getinfo(pyodbc.SQL_ODBC_VER)
    print 'driver:  %s %s' % (cnxn.getinfo(pyodbc.SQL_DRIVER_NAME), cnxn.getinfo(pyodbc.SQL_DRIVER_VER))
    print '         supports ODBC version %s' % cnxn.getinfo(pyodbc.SQL_DRIVER_ODBC_VER)
    print 'os:      %s' % platform.system()
    print 'unicode: Py_Unicode=%s SQLWCHAR=%s' % (pyodbc.UNICODE_SIZE, pyodbc.SQLWCHAR_SIZE)

    if platform.system() == 'Windows':
        print '         %s' % ' '.join([s for s in platform.win32_ver() if s])
项目:DBAdapter    作者:ContinuumIO    | 项目源码 | 文件源码
def print_library_info(cnxn):
    import pyodbc
    print('python:  %s' % sys.version)
    print('pyodbc:  %s %s' % (pyodbc.version, os.path.abspath(pyodbc.__file__)))
    print('odbc:    %s' % cnxn.getinfo(pyodbc.SQL_ODBC_VER))
    print('driver:  %s %s' % (cnxn.getinfo(pyodbc.SQL_DRIVER_NAME), cnxn.getinfo(pyodbc.SQL_DRIVER_VER)))
    print('         supports ODBC version %s' % cnxn.getinfo(pyodbc.SQL_DRIVER_ODBC_VER))
    print('os:      %s' % platform.system())
    print('unicode: Py_Unicode=%s SQLWCHAR=%s' % (pyodbc.UNICODE_SIZE, pyodbc.SQLWCHAR_SIZE))

    if platform.system() == 'Windows':
        print('         %s' % ' '.join([s for s in platform.win32_ver() if s]))
项目:TCP-IP    作者:JackZ0    | 项目源码 | 文件源码
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

# Just make sure we don't get pwned... Make sure that it also doesn't
# start with a period or have two consecutive periods <- this needs to
# be done in addition to the regex
项目:certbot    作者:nikoloskii    | 项目源码 | 文件源码
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'):
        os_ver = subprocess.Popen(
            ["sw_vers", "-productVersion"],
            stdout=subprocess.PIPE
        ).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

# Just make sure we don't get pwned... Make sure that it also doesn't
# start with a period or have two consecutive periods <- this needs to
# be done in addition to the regex
项目:oil    作者:oilshell    | 项目源码 | 文件源码
def test_main(verbose=False):
    if support.verbose:
        plats = {
            'Linux': platform.linux_distribution,
            'Mac': platform.mac_ver,
            'Windows': platform.win32_ver,
        }
        for name, func in plats.items():
            plat = func()
            if plat and plat[0]:
                plat = '%s %r' % (name, plat)
                break
        else:
            plat = repr(platform.platform())
        print("test_ssl: testing with %r %r" %
            (ssl.OPENSSL_VERSION, ssl.OPENSSL_VERSION_INFO))
        print("          under %s" % plat)
        print("          HAS_SNI = %r" % ssl.HAS_SNI)
        print("          OP_ALL = 0x%8x" % ssl.OP_ALL)
        try:
            print("          OP_NO_TLSv1_1 = 0x%8x" % ssl.OP_NO_TLSv1_1)
        except AttributeError:
            pass

    for filename in [
        CERTFILE, REMOTE_ROOT_CERT, BYTES_CERTFILE,
        ONLYCERT, ONLYKEY, BYTES_ONLYCERT, BYTES_ONLYKEY,
        SIGNED_CERTFILE, SIGNED_CERTFILE2, SIGNING_CA,
        BADCERT, BADKEY, EMPTYCERT]:
        if not os.path.exists(filename):
            raise support.TestFailed("Can't read certificate file %r" % filename)

    tests = [ContextTests, BasicTests, BasicSocketTests, SSLErrorTests]

    if support.is_resource_enabled('network'):
        tests.append(NetworkedTests)

    if _have_threads:
        thread_info = support.threading_setup()
        if thread_info:
            tests.append(ThreadedTests)

    try:
        support.run_unittest(*tests)
    finally:
        if _have_threads:
            support.threading_cleanup(*thread_info)
项目:python2-tracer    作者:extremecoders-re    | 项目源码 | 文件源码
def test_main(verbose=False):
    if support.verbose:
        plats = {
            'Linux': platform.linux_distribution,
            'Mac': platform.mac_ver,
            'Windows': platform.win32_ver,
        }
        for name, func in plats.items():
            plat = func()
            if plat and plat[0]:
                plat = '%s %r' % (name, plat)
                break
        else:
            plat = repr(platform.platform())
        print("test_ssl: testing with %r %r" %
            (ssl.OPENSSL_VERSION, ssl.OPENSSL_VERSION_INFO))
        print("          under %s" % plat)
        print("          HAS_SNI = %r" % ssl.HAS_SNI)
        print("          OP_ALL = 0x%8x" % ssl.OP_ALL)
        try:
            print("          OP_NO_TLSv1_1 = 0x%8x" % ssl.OP_NO_TLSv1_1)
        except AttributeError:
            pass

    for filename in [
        CERTFILE, REMOTE_ROOT_CERT, BYTES_CERTFILE,
        ONLYCERT, ONLYKEY, BYTES_ONLYCERT, BYTES_ONLYKEY,
        SIGNED_CERTFILE, SIGNED_CERTFILE2, SIGNING_CA,
        BADCERT, BADKEY, EMPTYCERT]:
        if not os.path.exists(filename):
            raise support.TestFailed("Can't read certificate file %r" % filename)

    tests = [ContextTests, BasicTests, BasicSocketTests, SSLErrorTests]

    if support.is_resource_enabled('network'):
        tests.append(NetworkedTests)

    if _have_threads:
        thread_info = support.threading_setup()
        if thread_info:
            tests.append(ThreadedTests)

    try:
        support.run_unittest(*tests)
    finally:
        if _have_threads:
            support.threading_cleanup(*thread_info)
项目:vivisect-py3    作者:bat-serjo    | 项目源码 | 文件源码
def __init__(self):

        self.casesens = False

        self.phandle = None
        self.thandles = {}
        self.win32threads = {}
        self.dosdevs = []
        self.flushcache = False
        self.faultaddr = None
        global dbgprivdone
        if not dbgprivdone:
            dbgprivdone = getDebugPrivileges()

        self._is_wow64 = False  # 64 bit trace uses this...
        self._step_suspends = set() # Threads we have suspended for single stepping

        # Skip the attach event and plow through to the first
        # injected breakpoint (cause libs are loaded by then)
        self.enableAutoContinue(vtrace.NOTIFY_ATTACH)

        self.setupDosDeviceMaps()

        # Setup our binary format meta
        self.setMeta('Format','pe')

        # Setup some win32_ver info in metadata
        rel,ver,csd,ptype = platform.win32_ver()
        self.setMeta("WindowsRelease",rel)
        self.setMeta("WindowsVersion", ver)
        self.setMeta("WindowsCsd", csd)
        self.setMeta("WindowsProcessorType", ptype)

        # Setup modes which only apply to windows systems
        self.initMode('BlockStep', False, 'Single step to branch entry points')

        # If possible, get a default set of struct definitions
        # for ntdll...
        nt = vs_windows.getCurrentDef('ntdll')
        if nt != None:
            self.vsbuilder.addVStructNamespace('ntdll', nt)

        # Either way, add the fallback "win32" namespace
        self.vsbuilder.addVStructNamespace('win32', vs_win32)

        # We need thread proxying for a few calls...
        self.fireTracerThread()
项目:covertutils    作者:operatorequals    | 项目源码 | 文件源码
def work( storage, message ) :
    # print( "Control message: %s" % message )

    if message == storage['commands']['reset'] :
        storage['COMMON']['handler'].reset()
        return 'OK'
    elif message == storage['commands']['identity'] :
        return storage['COMMON']['handler'].orchestrator.getIdentity()[:8]

    elif message == storage['commands']['kill'] :
        storage['COMMON']['handler'].stop()
        import threading
        kill_thread = threading.Thread(target = storage['wait_exit_func'])
        kill_thread.start()
        return "OK"

    elif message == storage['commands']['mute'] :
        # if (storage['COMMON']['handler'])     # If it is interrogating,
        storage['COMMON']['handler'].send_function = storage['dummy_send_func']
        return "OK" # just for the hell of it

    elif message == storage['commands']['unmute'] :
        storage['COMMON']['handler'].send_function = storage['real_send_func']
        return "OK" #

    elif message == storage['commands']['nuke'] :
        storage['nuke_func']()
        return "OK" #

    elif message == storage['commands']['sysinfo'] :
        import platform, json, getpass, locale
        ret = "+".join([                   # 113 bytes
            platform.node(),
            platform.machine(),
            platform.version(),
            '-'.join(locale.getdefaultlocale()),
            platform.platform(),
            platform.release(),
            platform.system(),
            platform.processor(),
            getpass.getuser(),
            '-'.join(platform.win32_ver()),
            '-'.join(platform.libc_ver()),
            # '-'.join(platform.mac_ver()),
        ])
        # ret = json.dumps(info).replace( " ","" )  # to save some bytes
        return ret
    else :
        return "N/A"
项目:pefile.pypy    作者:cloudtracer    | 项目源码 | 文件源码
def test_main(verbose=False):
    if support.verbose:
        plats = {
            'Linux': platform.linux_distribution,
            'Mac': platform.mac_ver,
            'Windows': platform.win32_ver,
        }
        for name, func in plats.items():
            plat = func()
            if plat and plat[0]:
                plat = '%s %r' % (name, plat)
                break
        else:
            plat = repr(platform.platform())
        print("test_ssl: testing with %r %r" %
            (ssl.OPENSSL_VERSION, ssl.OPENSSL_VERSION_INFO))
        print("          under %s" % plat)
        print("          HAS_SNI = %r" % ssl.HAS_SNI)
        print("          OP_ALL = 0x%8x" % ssl.OP_ALL)
        try:
            print("          OP_NO_TLSv1_1 = 0x%8x" % ssl.OP_NO_TLSv1_1)
        except AttributeError:
            pass

    for filename in [
        CERTFILE, SVN_PYTHON_ORG_ROOT_CERT, BYTES_CERTFILE,
        ONLYCERT, ONLYKEY, BYTES_ONLYCERT, BYTES_ONLYKEY,
        SIGNED_CERTFILE, SIGNED_CERTFILE2, SIGNING_CA,
        BADCERT, BADKEY, EMPTYCERT]:
        if not os.path.exists(filename):
            raise support.TestFailed("Can't read certificate file %r" % filename)

    tests = [ContextTests, BasicTests, BasicSocketTests, SSLErrorTests]

    if support.is_resource_enabled('network'):
        tests.append(NetworkedTests)

    if _have_threads:
        thread_info = support.threading_setup()
        if thread_info:
            tests.append(ThreadedTests)

    try:
        support.run_unittest(*tests)
    finally:
        if _have_threads:
            support.threading_cleanup(*thread_info)
项目:ouroboros    作者:pybee    | 项目源码 | 文件源码
def test_main(verbose=False):
    if support.verbose:
        plats = {
            'Linux': platform.linux_distribution,
            'Mac': platform.mac_ver,
            'Windows': platform.win32_ver,
        }
        for name, func in plats.items():
            plat = func()
            if plat and plat[0]:
                plat = '%s %r' % (name, plat)
                break
        else:
            plat = repr(platform.platform())
        print("test_ssl: testing with %r %r" %
            (ssl.OPENSSL_VERSION, ssl.OPENSSL_VERSION_INFO))
        print("          under %s" % plat)
        print("          HAS_SNI = %r" % ssl.HAS_SNI)
        print("          OP_ALL = 0x%8x" % ssl.OP_ALL)
        try:
            print("          OP_NO_TLSv1_1 = 0x%8x" % ssl.OP_NO_TLSv1_1)
        except AttributeError:
            pass

    for filename in [
        CERTFILE, REMOTE_ROOT_CERT, BYTES_CERTFILE,
        ONLYCERT, ONLYKEY, BYTES_ONLYCERT, BYTES_ONLYKEY,
        SIGNED_CERTFILE, SIGNED_CERTFILE2, SIGNING_CA,
        BADCERT, BADKEY, EMPTYCERT]:
        if not os.path.exists(filename):
            raise support.TestFailed("Can't read certificate file %r" % filename)

    tests = [ContextTests, BasicSocketTests, SSLErrorTests]

    if support.is_resource_enabled('network'):
        tests.append(NetworkedTests)

    if _have_threads:
        thread_info = support.threading_setup()
        if thread_info:
            tests.append(ThreadedTests)

    try:
        support.run_unittest(*tests)
    finally:
        if _have_threads:
            support.threading_cleanup(*thread_info)
项目:kbe_server    作者:xiaohaoppy    | 项目源码 | 文件源码
def test_main(verbose=False):
    if support.verbose:
        plats = {
            'Linux': platform.linux_distribution,
            'Mac': platform.mac_ver,
            'Windows': platform.win32_ver,
        }
        for name, func in plats.items():
            plat = func()
            if plat and plat[0]:
                plat = '%s %r' % (name, plat)
                break
        else:
            plat = repr(platform.platform())
        print("test_ssl: testing with %r %r" %
            (ssl.OPENSSL_VERSION, ssl.OPENSSL_VERSION_INFO))
        print("          under %s" % plat)
        print("          HAS_SNI = %r" % ssl.HAS_SNI)
        print("          OP_ALL = 0x%8x" % ssl.OP_ALL)
        try:
            print("          OP_NO_TLSv1_1 = 0x%8x" % ssl.OP_NO_TLSv1_1)
        except AttributeError:
            pass

    for filename in [
        CERTFILE, SVN_PYTHON_ORG_ROOT_CERT, BYTES_CERTFILE,
        ONLYCERT, ONLYKEY, BYTES_ONLYCERT, BYTES_ONLYKEY,
        SIGNED_CERTFILE, SIGNED_CERTFILE2, SIGNING_CA,
        BADCERT, BADKEY, EMPTYCERT]:
        if not os.path.exists(filename):
            raise support.TestFailed("Can't read certificate file %r" % filename)

    tests = [ContextTests, BasicSocketTests, SSLErrorTests]

    if support.is_resource_enabled('network'):
        tests.append(NetworkedTests)

    if _have_threads:
        thread_info = support.threading_setup()
        if thread_info:
            tests.append(ThreadedTests)

    try:
        support.run_unittest(*tests)
    finally:
        if _have_threads:
            support.threading_cleanup(*thread_info)
项目:vim-clangd    作者:Chilledheart    | 项目源码 | 文件源码
def _DetectBinaryUrl(self):
        platform_system = platform.system()
        if platform_system == 'Linux':
            linux_dist = platform.dist()
            # dist turple is like this
            # Ubuntu, 16.04, Xenial
            # or Debian, 8.8, ''
            # fix for debian
            if linux_dist[0].lower() == 'debian':
                linux_dist[1] = str(int(linux_dist[1]))
            platform_version = float(linux_dist[1])
            platform_desc = '%s %s' % (linux_dist[0], platform_version)
        elif platform_system == 'Darwin':
            v, _, _ = platform.mac_ver()
            mac_ver = '.'.join(v.split('.')[:2])
            platform_version = float(mac_ver)
            platform_desc = 'Mac OS X %s' % mac_ver
        elif platform_system == 'Windows':
            win_ver, _, _, _ = platform.win32_ver()
            platform_version = float(win_ver)
        elif platform_system.startswith('MINGW64_NT'):
            # use msvc binary temporarily
            win_ver = float(platform_system.split('-')[1])
            platform_system = 'Windows'
            platform_version = float(win_ver)
        else:
            platform_system = 'Unknown System'
            platform_version = 0.0

        if not platform_desc:
            platform_desc = '%s %f' % (platform_system, platform_version)

        log.warn('detected %s' % platform_desc)

        download_infos = self._LoadDownloadInfo()
        # try to match from a set of download infos
        plats = []
        for plat in download_infos:
            # not trust url outside our mirror site
            if not plat['url'].startswith(DOWNLOAD_URL_PREFIX):
                continue
            if plat['system'] == platform_system:
                if platform_system == 'Linux':
                    if plat['dist'][0].lower() != linux_dist[0].lower():
                        continue
                    plat['version'] = float(plat['dist'][1])
                elif platform_system == 'Darwin':
                    plat['version'] = float(plat['mac_ver'])
                elif platform_system == 'Windows':
                    plat['version'] = float(plat['win_ver'])
                if platform_version < plat['version']:
                    continue
                plats.append(plat)
        if not plats:
            return platform_desc, None
        plats.sort(key=lambda x : x['version'], reverse=True)
        return platform_desc, plats[0]
项目:homeassistant    作者:NAStools    | 项目源码 | 文件源码
def get_newest_version(huuid):
    """Get the newest Home Assistant version."""
    info_object = {
        'arch': platform.machine(),
        'dev': ('dev' in CURRENT_VERSION),
        'docker': False,
        'os_name': platform.system(),
        'python_version': platform.python_version(),
        'timezone': dt_util.DEFAULT_TIME_ZONE.zone,
        'uuid': huuid,
        'version': CURRENT_VERSION,
        'virtualenv': (os.environ.get('VIRTUAL_ENV') is not None),
    }

    if platform.system() == 'Windows':
        info_object['os_version'] = platform.win32_ver()[0]
    elif platform.system() == 'Darwin':
        info_object['os_version'] = platform.mac_ver()[0]
    elif platform.system() == 'FreeBSD':
        info_object['os_version'] = platform.release()
    elif platform.system() == 'Linux':
        import distro
        linux_dist = distro.linux_distribution(full_distribution_name=False)
        info_object['distribution'] = linux_dist[0]
        info_object['os_version'] = linux_dist[1]
        info_object['docker'] = os.path.isfile('/.dockerenv')

    if not huuid:
        info_object = {}

    res = None
    try:
        req = requests.post(UPDATER_URL, json=info_object, timeout=5)
        res = req.json()
        res = RESPONSE_SCHEMA(res)

        _LOGGER.info(("Submitted analytics to Home Assistant servers. "
                      "Information submitted includes %s"), info_object)
        return (res['version'], res['release-notes'])
    except requests.RequestException:
        _LOGGER.error("Could not contact Home Assistant Update to check "
                      "for updates")
        return None

    except ValueError:
        _LOGGER.error("Received invalid response from Home Assistant Update")
        return None

    except vol.Invalid:
        _LOGGER.error('Got unexpected response: %s', res)
        return None