我需要看些什么来确定我使用的是Windows还是Unix等等?


当前回答

>>> import os
>>> os.name
'posix'
>>> import platform
>>> platform.system()
'Linux'
>>> platform.release()
'2.6.22-15-generic'

platform.system()的输出如下:

Linux: Linux 麦克:达尔文 Windows:

参见:平台-访问底层平台的识别数据

其他回答

下面是Mac上的测试结果:

>>> import os
>>> os.name
'posix'
>>> import platform
>>> platform.system()
'Darwin'
>>> platform.release()
'8.11.1'

如果你运行macOS X并运行platform.system(),你会得到darwin 因为macOS X是基于苹果的达尔文操作系统构建的。Darwin是macOS X的内核,本质上是没有GUI的macOS X。

使用Python区分操作系统的示例代码:

import sys

if sys.platform.startswith("linux"):  # could be "linux", "linux2", "linux3", ...
    # linux
elif sys.platform == "darwin":
    # MAC OS X
elif os.name == "nt":
    # Windows, Cygwin, etc. (either 32-bit or 64-bit)

像下面这样一个简单的Enum实现怎么样?不需要外部库!

import platform
from enum import Enum
class OS(Enum):
    def checkPlatform(osName):
        return osName.lower()== platform.system().lower()

    MAC = checkPlatform("darwin")
    LINUX = checkPlatform("linux")
    WINDOWS = checkPlatform("windows")  #I haven't test this one

简单地,您可以使用Enum值访问

if OS.LINUX.value:
    print("Cool it is Linux")

附注:它是python3

一个新的答案如何:

import psutil
psutil.MACOS   #True (OSX is deprecated)
psutil.WINDOWS #False
psutil.LINUX   #False 

如果我使用MACOS,这将是输出