我如何检查我'm运行在Windows上的Python?

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

问题是,如何实现?

if is_windows():
...

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


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

246539 次浏览

Python 操作系统模块

特别针对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()

.系统相关版本信息

平台模块提供

.系统标识的详细检查

你应该能够依赖__abc1 .name。

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

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

在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.

如果这不起作用,也许可以尝试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可能是可行的,就像其他人提到的那样。

人力资源> < p > < 这里有一些他们在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())

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