我找到了平台模块,但它说它返回'Windows',它在我的机器上返回'Microsoft'。我注意到在stackoverflow上的另一个线程有时会返回'Vista'。

问题是,如何实现?

if is_windows():
  ...

以一种向前兼容的方式?如果我必须检查像“Vista”这样的东西,那么当windows的下一个版本出来时,它就会崩溃。


注意:声称这是一个重复问题的答案实际上并没有回答is_windows问题。他们回答了“什么平台”的问题。由于存在多种类型的窗口,没有一种能够全面描述如何获得isWindows的答案。


Python操作系统模块

特别针对Python 3.6/3.7:

os.name:操作系统的名称 已导入系统相关模块。的 以下名称目前已 已注册:'posix', 'nt', 'java'。

在你的例子中,你想检查os.name输出是否有'nt':

import os

if os.name == 'nt':
     ...

os.name上还有一个注释:

参见sys。平台具有更细的粒度。os.uname()给 系统相关版本信息。 平台模块提供 系统标识的详细检查。

您应该能够依赖os.name。

import os
if os.name == 'nt':
    # ...

编辑:现在我想说的是,最清晰的方法是通过平台模块,就像其他答案一样。

在sys too中:

import sys
# its win32, maybe there is win64 too?
is_windows = sys.platform.startswith('win')

你用的是platform.system吗?

 system()
        Returns the system/OS name, e.g. 'Linux', 'Windows' or 'Java'.

        An empty string is returned if the value cannot be determined.

如果还不行,可以试试平台。win32_ver如果它没有抛出异常,说明你在Windows上;但我不知道它是否向前兼容64位,因为它的名称中有32位。

win32_ver(release='', version='', csd='', ptype='')
        Get additional version information from the Windows Registry
        and return a tuple (version,csd,ptype) referring to version
        number, CSD level and OS type (multi/single
        processor).

但是os.name可能是可行的方法,就像其他人提到的那样。

这里有一些他们在platform.py中检查Windows的方法:

if sys.platform == 'win32':
#---------
if os.environ.get('OS','') == 'Windows_NT':
#---------
try: import win32api
#---------
# Emulation using _winreg (added in Python 2.0) and
# sys.getwindowsversion() (added in Python 2.3)
import _winreg
GetVersionEx = sys.getwindowsversion
#----------
def system():

    """ Returns the system/OS name, e.g. 'Linux', 'Windows' or 'Java'.    
        An empty string is returned if the value cannot be determined.   
    """
    return uname()[0]
import platform
is_windows = any(platform.win32_ver())

or

import sys
is_windows = hasattr(sys, 'getwindowsversion')