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

339 投票
5 回答
293403 浏览
提问于 2025-04-15 13:51

我发现了一个平台模块,但它说会返回'Windows',而在我的电脑上却返回'Microsoft'。我注意到在StackOverflow的另一个讨论中,有时它会返回'Vista'。

所以,问题是,我该怎么实现呢?

if is_windows():
  ...

以一种向前兼容的方式?如果我需要检查像'Vista'这样的东西,那么在下一个版本的Windows发布时就会出问题。


注意:那些声称这是重复问题的回答其实并没有真正回答is_windows这个问题。它们回答的是“是什么平台”。因为Windows有很多不同的版本,所以没有一个答案能全面描述如何得到isWindows的结果。

5 个回答

52

你可以依靠 os 这个模块里的 .name 属性。

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

补充一下:现在我觉得最简单明了的方法是通过 platform 模块,正如其他回答所提到的。

88

你在用 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]
514

Python的os模块

特别是针对Python 3.6/3.7版本:

os.name:这是一个用来表示操作系统类型的模块名。现在已经注册的名称有:'posix'、'nt'和'java'。

在你的情况下,你想要检查的就是os.name的输出是否为'nt':

import os

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

关于os.name还有一个补充说明:

你还可以查看sys.platform,它提供了更详细的信息。os.uname()可以给出系统相关的版本信息。

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

撰写回答