Python sys.getwindowsversion() Examples

The following are 30 code examples of sys.getwindowsversion(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module sys , or try the search function .
Example #1
Source File: __init__.py    From vnpy_crypto with MIT License 6 votes vote down vote up
def get_winver():
    if not WINDOWS:
        raise NotImplementedError("not WINDOWS")
    wv = sys.getwindowsversion()
    if hasattr(wv, 'service_pack_major'):  # python >= 2.7
        sp = wv.service_pack_major or 0
    else:
        r = re.search(r"\s\d$", wv[4])
        if r:
            sp = int(r.group(0))
        else:
            sp = 0
    return (wv[0], wv[1], sp)


# ===================================================================
# --- sync primitives
# =================================================================== 
Example #2
Source File: utils.py    From tvalacarta with GNU General Public License v3.0 6 votes vote down vote up
def encodeFilename(s, for_subprocess=False):
    """
    @param s The name of the file
    """

    assert type(s) == compat_str

    # Python 3 has a Unicode API
    if sys.version_info >= (3, 0):
        return s

    # Pass '' directly to use Unicode APIs on Windows 2000 and up
    # (Detecting Windows NT 4 is tricky because 'major >= 4' would
    # match Windows 9x series as well. Besides, NT 4 is obsolete.)
    if not for_subprocess and sys.platform == 'win32' and sys.getwindowsversion()[0] >= 5:
        return s

    # Jython assumes filenames are Unicode strings though reported as Python 2.x compatible
    if sys.platform.startswith('java'):
        return s

    return s.encode(get_subprocess_encoding(), 'ignore') 
Example #3
Source File: utils.py    From youtube-dl-GUI with MIT License 6 votes vote down vote up
def encodeFilename(s, for_subprocess=False):
    """
    @param s The name of the file
    """

    assert type(s) == compat_str

    # Python 3 has a Unicode API
    if sys.version_info >= (3, 0):
        return s

    # Pass '' directly to use Unicode APIs on Windows 2000 and up
    # (Detecting Windows NT 4 is tricky because 'major >= 4' would
    # match Windows 9x series as well. Besides, NT 4 is obsolete.)
    if not for_subprocess and sys.platform == 'win32' and sys.getwindowsversion()[0] >= 5:
        return s

    # Jython assumes filenames are Unicode strings though reported as Python 2.x compatible
    if sys.platform.startswith('java'):
        return s

    return s.encode(get_subprocess_encoding(), 'ignore') 
Example #4
Source File: classifier.py    From vsc with MIT License 6 votes vote down vote up
def _mss_bugfix(self):
        """Temporary windows DPI bugfix for mss"""

        os_ = platform.system().lower()
        if os_ == "windows":
            version = sys.getwindowsversion()[:2]
            if version >= (6, 3):
                # Windows 8.1+
                # Here 2 = PROCESS_PER_MONITOR_DPI_AWARE, which means:
                #     per monitor DPI aware. This app checks for the DPI when it is
                #     created and adjusts the scale factor whenever the DPI changes.
                #     These applications are not automatically scaled by the system.
                ctypes.windll.shcore.SetProcessDpiAwareness(2)
            elif (6, 0) <= version < (6, 3):
                # Windows Vista, 7, 8 and Server 2012
                ctypes.windll.user32.SetProcessDPIAware() 
Example #5
Source File: requirements_check.py    From textext with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def __init__(self):
        super(WindowsDefaults, self)
        from .win_app_paths import get_non_syspath_dirs
        self._tweaked_syspath = get_non_syspath_dirs() + os.environ["PATH"].split(os.path.pathsep)

        # Windows 10 supports colored output since anniversary update (build 14393)
        # so we try to use it (it has to be enabled since it is always disabled by default!)
        try:
            wininfo = sys.getwindowsversion()
            if wininfo.major >= 10 and wininfo.build >= 14393:

                import ctypes as ct
                h_kernel32 = ct.windll.kernel32

                #  STD_OUTPUT_HANDLE = -11
                # -> https://docs.microsoft.com/en-us/windows/console/getstdhandle
                h_stdout = h_kernel32.GetStdHandle(-11)

                # ENABLE_PROCESSED_OUTPUT  | ENABLE_WRAP_AT_EOL_OUTPUT | ENABLE_VIRTUAL_TERMINAL_PROCESSING = 7
                # -> https://docs.microsoft.com/en-us/windows/console/setconsolemode
                result = h_kernel32.SetConsoleMode(h_stdout, 7)

                self.console_colors = "always"
        except (ImportError, AttributeError):
            pass 
Example #6
Source File: __init__.py    From Galaxy_Plugin_Bethesda with MIT License 6 votes vote down vote up
def get_winver():
    if not WINDOWS:
        raise NotImplementedError("not WINDOWS")
    wv = sys.getwindowsversion()
    if hasattr(wv, 'service_pack_major'):  # python >= 2.7
        sp = wv.service_pack_major or 0
    else:
        r = re.search(r"\s\d$", wv[4])
        if r:
            sp = int(r.group(0))
        else:
            sp = 0
    return (wv[0], wv[1], sp)


# ===================================================================
# --- sync primitives
# =================================================================== 
Example #7
Source File: utils.py    From anime-dl with MIT License 6 votes vote down vote up
def encodeFilename(s, for_subprocess=False):
    """
    @param s The name of the file
    """

    assert type(s) == compat_str

    # Python 3 has a Unicode API
    if sys.version_info >= (3, 0):
        return s

    # Pass '' directly to use Unicode APIs on Windows 2000 and up
    # (Detecting Windows NT 4 is tricky because 'major >= 4' would
    # match Windows 9x series as well. Besides, NT 4 is obsolete.)
    if not for_subprocess and sys.platform == 'win32' and sys.getwindowsversion()[0] >= 5:
        return s

    # Jython assumes filenames are Unicode strings though reported as Python 2.x compatible
    if sys.platform.startswith('java'):
        return s

    return s.encode(get_subprocess_encoding(), 'ignore') 
Example #8
Source File: __init__.py    From psutil with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def get_winver():
    if not WINDOWS:
        raise NotImplementedError("not WINDOWS")
    wv = sys.getwindowsversion()
    if hasattr(wv, 'service_pack_major'):  # python >= 2.7
        sp = wv.service_pack_major or 0
    else:
        r = re.search(r"\s\d$", wv[4])
        if r:
            sp = int(r.group(0))
        else:
            sp = 0
    return (wv[0], wv[1], sp)


# ===================================================================
# --- sync primitives
# =================================================================== 
Example #9
Source File: test_system.py    From vnpy_crypto with MIT License 6 votes vote down vote up
def test_cpu_count(self):
        logical = psutil.cpu_count()
        self.assertEqual(logical, len(psutil.cpu_times(percpu=True)))
        self.assertGreaterEqual(logical, 1)
        #
        if os.path.exists("/proc/cpuinfo"):
            with open("/proc/cpuinfo") as fd:
                cpuinfo_data = fd.read()
            if "physical id" not in cpuinfo_data:
                raise unittest.SkipTest("cpuinfo doesn't include physical id")
        physical = psutil.cpu_count(logical=False)
        if WINDOWS and sys.getwindowsversion()[:2] <= (6, 1):  # <= Vista
            self.assertIsNone(physical)
        else:
            self.assertGreaterEqual(physical, 1)
            self.assertGreaterEqual(logical, physical) 
Example #10
Source File: recipe-334779.py    From code with MIT License 6 votes vote down vote up
def __init__(self, gtk_window):

        self._window = gtk_window
        self._hwnd = gtk_window.window.handle

        self._message_map = {}

        # Windows transparency is only supported windows2000 and above.
        if sys.getwindowsversion()[0] <= 4:
            self.alpha = None
        else:
            self.alpha = 100
            self._transparency = False

        self.notify_icon = None            

        # Sublass the window and inject a WNDPROC to process messages.
        self._oldwndproc = win32gui.SetWindowLong(self._hwnd, GWL_WNDPROC,
                                                  self._wndproc)

        gtk_window.connect('unrealize', self.remove) 
Example #11
Source File: register.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def UseCommandLine(*classes, **flags):
  unregisterInfo = '--unregister_info' in sys.argv
  unregister = '--unregister' in sys.argv
  flags['quiet'] = flags.get('quiet',0) or '--quiet' in sys.argv
  flags['debug'] = flags.get('debug',0) or '--debug' in sys.argv
  flags['unattended'] = flags.get('unattended',0) or '--unattended' in sys.argv
  if unregisterInfo:
    return UnregisterInfoClasses(*classes, **flags)
  try:
    if unregister:
      UnregisterClasses(*classes, **flags)
    else:
      RegisterClasses(*classes, **flags)
  except win32api.error, exc:
    # If we are on xp+ and have "access denied", retry using
    # ShellExecuteEx with 'runas' verb to force elevation (vista) and/or
    # admin login dialog (vista/xp)
    if flags['unattended'] or exc.winerror != winerror.ERROR_ACCESS_DENIED \
       or sys.getwindowsversion()[0] < 5:
      raise
    ReExecuteElevated(flags) 
Example #12
Source File: win32timezone.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def resolveMUITimeZone(spec):
	"""Resolve a multilingual user interface resource for the time zone name
	>>> #some pre-amble for the doc-tests to be py2k and py3k aware)
	>>> try: unicode and None
	... except NameError: unicode=str
	...
	>>> result = resolveMUITimeZone('@tzres.dll,-110')
	>>> expectedResultType = [type(None),unicode][sys.getwindowsversion() >= (6,)]
	>>> type(result) is expectedResultType
	True
	
	spec should be of the format @path,-stringID[;comment]
	see http://msdn2.microsoft.com/en-us/library/ms725481.aspx for details
	"""
	pattern = re.compile('@(?P<dllname>.*),-(?P<index>\d+)(?:;(?P<comment>.*))?')
	matcher = pattern.match(spec)
	assert matcher, 'Could not parse MUI spec'

	try:
		handle = DLLCache[matcher.groupdict()['dllname']]
		result = win32api.LoadString(handle, int(matcher.groupdict()['index']))
	except win32api.error, e:
		result = None 
Example #13
Source File: winmanifest.py    From ConTroll_Remote_Access_Trojan with Apache License 2.0 6 votes vote down vote up
def getlanguage(self, language=None, windowsversion=None):
        """
        Get and return the manifest's language as string.
        
        Can be either language-culture e.g. 'en-us' or a string indicating 
        language neutrality, e.g. 'x-ww' on Windows XP or 'none' on Vista 
        and later.
        
        """
        if not language:
            language = self.language
        if language in (None, "", "*", "neutral"):
            return (LANGUAGE_NEUTRAL_NT5,
                    LANGUAGE_NEUTRAL_NT6)[(windowsversion or 
                                           sys.getwindowsversion()) >= (6, )]
        return language 
Example #14
Source File: __init__.py    From jarvis with GNU General Public License v2.0 6 votes vote down vote up
def get_winver():
    if not WINDOWS:
        raise NotImplementedError("not WINDOWS")
    wv = sys.getwindowsversion()
    if hasattr(wv, 'service_pack_major'):  # python >= 2.7
        sp = wv.service_pack_major or 0
    else:
        r = re.search(r"\s\d$", wv[4])
        if r:
            sp = int(r.group(0))
        else:
            sp = 0
    return (wv[0], wv[1], sp)


# ===================================================================
# --- sync primitives
# =================================================================== 
Example #15
Source File: _pswindows.py    From Galaxy_Plugin_Bethesda with MIT License 5 votes vote down vote up
def get_winver():
    """Usage:
    >>> if get_winver() <= WIN_VISTA:
    ...      ...
    """
    wv = sys.getwindowsversion()
    return (wv.major, wv.minor) 
Example #16
Source File: test_sys.py    From CTFCrackTools-V2 with GNU General Public License v3.0 5 votes vote down vote up
def test_getwindowsversion(self):
        if hasattr(sys, "getwindowsversion"):
            v = sys.getwindowsversion()
            self.assert_(isinstance(v, tuple))
            self.assertEqual(len(v), 5)
            self.assert_(isinstance(v[0], int))
            self.assert_(isinstance(v[1], int))
            self.assert_(isinstance(v[2], int))
            self.assert_(isinstance(v[3], int))
            self.assert_(isinstance(v[4], str)) 
Example #17
Source File: win.py    From luci-py with Apache License 2.0 5 votes vote down vote up
def get_os_version_names():
  """Returns the marketing/user-friendly names of the OS.

  The return value contains the base marketing name, e.g. Vista, 10, or
  2008Server. For Windows Server starting with 2016, this value is always
  "Server".

  For versions released before Windows 10, the return value also contains the
  name with the service pack, e.g. 7-SP1 or 2012ServerR2-SP0.

  For Windows 10 and Windows Server starting with 2016, the return value
  includes "10-" or "Server-" followed by one or more parts of the build number.
  E.g. for Windows 10 with build number 18362.207, the return value includes
  10-18362, 10-18362.207. For Windows Server 2019 with build number 17763.557,
  the return value includes Server-17763, Server-17763.557.
  """
  # Python keeps a local map in platform.py and it is updated at newer python
  # release. Since our python release is a bit old, do not rely on it.
  is_server = sys.getwindowsversion().product_type != 1
  lookup = _WIN32_SERVER_NAMES if is_server else _WIN32_CLIENT_NAMES
  version_number, build_number = _get_os_numbers()
  marketing_name = lookup.get(version_number, version_number)
  if version_number == u'10.0':
    rv = [marketing_name]
    # Windows 10 doesn't have service packs, the build number now is the
    # reference number. More discussion in
    # https://docs.google.com/document/d/1iF1tbc1oedCQ9J6aL7sHeuaayY3bs52fuvKxvLLZ0ig
    if '.' in build_number:
      major_version = build_number.split(u'.')[0]
      rv.append(u'%s-%s' % (marketing_name, major_version))
    rv.append(u'%s-%s' % (marketing_name, build_number))
    rv.sort()
    return rv
  service_pack = platform.win32_ver()[2] or u'SP0'
  return [marketing_name, u'%s-%s' % (marketing_name, service_pack)] 
Example #18
Source File: utils.py    From anime-dl with MIT License 5 votes vote down vote up
def get_subprocess_encoding():
    if sys.platform == 'win32' and sys.getwindowsversion()[0] >= 5:
        # For subprocess calls, encode with locale encoding
        # Refer to http://stackoverflow.com/a/9951851/35070
        encoding = preferredencoding()
    else:
        encoding = sys.getfilesystemencoding()
    if encoding is None:
        encoding = 'utf-8'
    return encoding 
Example #19
Source File: _winconsole.py    From vistir with ISC License 5 votes vote down vote up
def _wrap_std_stream(name):
    # Python 2 & Windows 7 and below
    if PY2 and sys.getwindowsversion()[:2] <= (6, 1) and name not in _wrapped_std_streams:
        setattr(sys, name, WindowsChunkedWriter(getattr(sys, name)))
        _wrapped_std_streams.add(name) 
Example #20
Source File: helpers.py    From py7zr with GNU Lesser General Public License v2.1 5 votes vote down vote up
def islink(path):
    """
    Cross-platform islink implementation.
    Supports Windows NT symbolic links and reparse points.
    """
    is_symlink = os.path.islink(str(path))
    if sys.version_info >= (3, 8) or sys.platform != "win32" or sys.getwindowsversion()[0] < 6:
        return is_symlink
    # special check for directory junctions which py38 does.
    if is_symlink:
        if py7zr.win32compat.is_reparse_point(path):
            is_symlink = False
    return is_symlink 
Example #21
Source File: _winconsole.py    From rules_pip with MIT License 5 votes vote down vote up
def _wrap_std_stream(name):
    # Python 2 & Windows 7 and below
    if (
        PY2
        and sys.getwindowsversion()[:2] <= (6, 1)
        and name not in _wrapped_std_streams
    ):
        setattr(sys, name, WindowsChunkedWriter(getattr(sys, name)))
        _wrapped_std_streams.add(name) 
Example #22
Source File: __main__.py    From angr-management with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def set_app_user_model_id():
    # Explicitly call SetCurrentProcessExplicitAppUserModelID() so the taskbar icon is displayed correctly.

    if sys.platform == 'win32':
        winver = sys.getwindowsversion()
        if winver.major >= 5:
            myappid = u'angr-management'
            ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(myappid) 
Example #23
Source File: kex.py    From kex with MIT License 5 votes vote down vote up
def get_haldisp_offsets():
	(halbase, dllname) = find_driver_base("hal.dll")
	version = sys.getwindowsversion()
	p = platfrom.platform()
	a = platform.architecture()[0]
	if a == '32bit':
		if((version.major == 5) and (version.minor == 1) and ('3' in version.service_pack)):
			# the target machine's OS is Windows XP SP3
			HaliQuerySystemInformation = halbase+0x16bba # Offset for XPSP3
			HalpSetSystemInformation   = halbase+0x19436 # Offset for XPSP3
		elif((version.major == 5) and (version.minor == 2) and ('2' in version.service_pack)):
			# the target machine's OS is Windows Server 2003 SP2
			HaliQuerySystemInformation = halbase+0x1fa1e # Offset for WIN2K3
			HalpSetSystemInformation   = halbase+0x21c60 # Offset for WIN2K3
		elif((version.major == 6) and (version.minor == 1) and ('1' in version.service_pack)):
			# the target machine's OS is Windows 7x86 SP1
			HaliQuerySystemInformation = halbase+0x278a2 # Offset for WIN7SP1x86
			HalpSetSystemInformation   = halbase+0x281b4 # Offset for WIN7SP1x86
		else:
			print "[-] No info about HaliQuerySystemInformation and HalpSetSystemInformation for this OS version"
			print "[-] Exiting..."
			sys.exit(-1)
	else:
		if((version.major == 6) and (version.minor == 1) and ('1' in version.service_pack)):
			# the target machine's OS is Windows 7x64 SP1
			HaliQuerySystemInformation = halbase+0x398e8 # Offset for win7 x64
			HalpSetSystemInformation = 0
		else:
			print "[-] No info about HaliQuerySystemInformation and HalpSetSystemInformation for this OS version"
			print "[-] Exiting..."
			sys.exit(-1)

	print "[+] HaliQuerySystemInformation address: %s" % hex(HaliQuerySystemInformation)
	print "[+] HalpSetSystemInformation address: %s" % hex(HalpSetSystemInformation)
	return (HaliQuerySystemInformation,HalpSetSystemInformation) 
Example #24
Source File: WatchUcsGui.py    From UcsPythonSDK with Apache License 2.0 5 votes vote down vote up
def GetUCSDefaultLogpathWindows ():
	if 'APPDATA' in os.environ.keys():
		logFilePath = os.getenv('APPDATA')
	else:
		print os.name
		raise 'Not windows OS'

	if sys.getwindowsversion()[0] == 6: ## in case OS is Win 2008 or above
		logFilePath = dirname(logFilePath) + "\LocalLow"
	logFilePath += r"\Sun\Java\Deployment\log\.ucsm" + "\\"
	return logFilePath 
Example #25
Source File: test_sys.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def test_getwindowsversion(self):
        # Raise SkipTest if sys doesn't have getwindowsversion attribute
        test.support.get_attribute(sys, "getwindowsversion")
        v = sys.getwindowsversion()
        self.assertEqual(len(v), 5)
        self.assertIsInstance(v[0], int)
        self.assertIsInstance(v[1], int)
        self.assertIsInstance(v[2], int)
        self.assertIsInstance(v[3], int)
        self.assertIsInstance(v[4], str)
        self.assertRaises(IndexError, operator.getitem, v, 5)
        self.assertIsInstance(v.major, int)
        self.assertIsInstance(v.minor, int)
        self.assertIsInstance(v.build, int)
        self.assertIsInstance(v.platform, int)
        self.assertIsInstance(v.service_pack, str)
        self.assertIsInstance(v.service_pack_minor, int)
        self.assertIsInstance(v.service_pack_major, int)
        self.assertIsInstance(v.suite_mask, int)
        self.assertIsInstance(v.product_type, int)
        self.assertEqual(v[0], v.major)
        self.assertEqual(v[1], v.minor)
        self.assertEqual(v[2], v.build)
        self.assertEqual(v[3], v.platform)
        self.assertEqual(v[4], v.service_pack)

        # This is how platform.py calls it. Make sure tuple
        #  still has 5 elements
        maj, min, buildno, plat, csd = sys.getwindowsversion() 
Example #26
Source File: __init__.py    From scalyr-agent-2 with Apache License 2.0 5 votes vote down vote up
def backend():
    """
    :return:
        A unicode string of the backend being used: "openssl", "osx", "win",
        "winlegacy"
    """

    if _module_values['backend'] is not None:
        return _module_values['backend']

    with _backend_lock:
        if _module_values['backend'] is not None:
            return _module_values['backend']

        if sys.platform == 'win32':
            # Windows XP was major version 5, Vista was 6
            if sys.getwindowsversion()[0] < 6:
                _module_values['backend'] = 'winlegacy'
            else:
                _module_values['backend'] = 'win'
        elif sys.platform == 'darwin':
            _module_values['backend'] = 'osx'
        else:
            _module_values['backend'] = 'openssl'

        return _module_values['backend'] 
Example #27
Source File: test_sys.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def test_sys_getwindowsversion_no_instantiation(self):
        # Skip if not being run on Windows.
        test.support.get_attribute(sys, "getwindowsversion")
        self.assert_raise_on_new_sys_type(sys.getwindowsversion()) 
Example #28
Source File: test_sys.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def assert_raise_on_new_sys_type(self, sys_attr):
        # Users are intentionally prevented from creating new instances of
        # sys.flags, sys.version_info, and sys.getwindowsversion.
        attr_type = type(sys_attr)
        with self.assertRaises(TypeError):
            attr_type()
        with self.assertRaises(TypeError):
            attr_type.__new__(attr_type) 
Example #29
Source File: test_sys.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def test_getwindowsversion(self):
        # Raise SkipTest if sys doesn't have getwindowsversion attribute
        test.support.get_attribute(sys, "getwindowsversion")
        v = sys.getwindowsversion()
        self.assertEqual(len(v), 5)
        self.assertIsInstance(v[0], int)
        self.assertIsInstance(v[1], int)
        self.assertIsInstance(v[2], int)
        self.assertIsInstance(v[3], int)
        self.assertIsInstance(v[4], str)
        self.assertRaises(IndexError, operator.getitem, v, 5)
        self.assertIsInstance(v.major, int)
        self.assertIsInstance(v.minor, int)
        self.assertIsInstance(v.build, int)
        self.assertIsInstance(v.platform, int)
        self.assertIsInstance(v.service_pack, str)
        self.assertIsInstance(v.service_pack_minor, int)
        self.assertIsInstance(v.service_pack_major, int)
        self.assertIsInstance(v.suite_mask, int)
        self.assertIsInstance(v.product_type, int)
        self.assertEqual(v[0], v.major)
        self.assertEqual(v[1], v.minor)
        self.assertEqual(v[2], v.build)
        self.assertEqual(v[3], v.platform)
        self.assertEqual(v[4], v.service_pack)

        # This is how platform.py calls it. Make sure tuple
        #  still has 5 elements
        maj, min, buildno, plat, csd = sys.getwindowsversion() 
Example #30
Source File: runtime.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def isVista(self):
        """
        Check if current platform is Windows Vista or Windows Server 2008.

        @return: C{True} if the current platform has been detected as Vista
        @rtype: C{bool}
        """
        if getattr(sys, "getwindowsversion", None) is not None:
            return sys.getwindowsversion()[0] == 6
        else:
            return False