2009-08-25 106 views
131

我找到了平台模块,但它说它返回'Windows',它在我的机器上返回'Microsoft'。我注意到在stackoverflow的另一个线程中它有时会返回'Vista'。如何检查我是否在Python的Windows上运行?

那么,问题是,如何实施?

if isWindows(): 
    ... 

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


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

+0

类似于http://计算器。com/questions/196930/how-to-check-if-os-is-vista-in-python – monkut 2009-08-25 01:27:14

+3

“应该有一个 - 最好只有一个 - 明显的方法来做到这一点。”唉,Python给了我们至少三种方法.. – 2009-08-25 01:35:33

回答

175

的Python os模块

具体地说

os.name进口操作 系统相关模块的名称。 以下名称目前已被 注册:'posix','nt','mac', 'os2','ce','java','riscos'。

在你的情况,你要检查 'NT' 为os.name输出:

import os 

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

'nt'是windows的值 – shuckc 2014-02-26 15:12:22

+0

linux通常返回什么? POSIX? – 2014-04-18 17:41:30

+1

@AndiJay - 是的,但应该很容易测试! – 2014-04-18 17:42:50

39

您应该能够依靠os。名称。

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

编辑:现在我要说到做到这一点最明显的方法是通过platform模块,按照对方的回答。

18

在sys太:

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

我在64位Windows上,这给了我'win32':) – Hut8 2016-02-09 20:57:20

38

是否使用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] 
+0

在64位机器上,Windows 7(64位操作系统),这是输出: Python 3.1.1(r311:74483,Aug 17 ('post2008Server','6.1,2009,16:45:59)[MSC v.1500 64 bit(AMD64)] on win32 >>> print(sys.platform) win32 >>> platform.win32_ver() .7100','','多处理器免费') 请注意,构建明确称它为win32。 – Francesco 2009-08-25 21:17:31

+0

糟糕,我认为输出格式会更好。希望你能阅读它。 – Francesco 2009-08-25 21:18:03

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

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