如何检查我是否在Python上运行Windows?

时间:2009-08-25 01:15:33

标签: python

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

所以,问题是,如何实施?

if isWindows():
  ...

以向前兼容的方式?如果我必须检查“Vista”之类的东西,那么当下一个版本的Windows出现时它就会中断。


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

5 个答案:

答案 0 :(得分:254)

Python os模块

专门针对Python 3.6 / 3.7:

  

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

在您的情况下,您要检查'nt'为os.name输出:

import os

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

os.name还有一条说明:

  

另请参见sys.platform具有更精细的粒度。 os.uname()给出了   系统相关的版本信息。

     

platform模块提供   详细检查系统的身份。

答案 1 :(得分:45)

您使用的是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.

如果这不起作用,可以尝试platform.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]

答案 2 :(得分:42)

您应该可以依赖os。name。

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

编辑:现在我要说最明智的方法是通过platform模块,按照另一个答案。

答案 3 :(得分:23)

在sys中也是

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

答案 4 :(得分:9)

import platform
is_windows = any(platform.win32_ver())

import sys
is_windows = hasattr(sys, 'getwindowsversion')
相关问题