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


当前回答

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

其他回答

同样的,....

import platform
is_windows=(platform.system().lower().find("win") > -1)

if(is_windows): lv_dll=LV_dll("my_so_dll.dll")
else:           lv_dll=LV_dll("./my_so_dll.so")

你也可以使用sys。平台,如果你已经导入了sys,你不想导入另一个模块

>>> import sys
>>> sys.platform
'linux2'

像下面这样一个简单的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

有很多方法可以找到这个最简单的方法就是使用OS包

import os 
print(os.name)

如果你想要用户可读的数据但仍然是详细的,你可以使用platform.platform()

>>> import platform
>>> platform.platform()
'Linux-3.3.0-8.fc16.x86_64-x86_64-with-fedora-16-Verne'

这里有几个不同的调用,你可以用它来确定你的位置,linux_distribution和dist在最近的python版本中被删除了。

import platform
import sys

def linux_distribution():
  try:
    return platform.linux_distribution()
  except:
    return "N/A"

def dist():
  try:
    return platform.dist()
  except:
    return "N/A"

print("""Python version: %s
dist: %s
linux_distribution: %s
system: %s
machine: %s
platform: %s
uname: %s
version: %s
mac_ver: %s
""" % (
sys.version.split('\n'),
str(dist()),
linux_distribution(),
platform.system(),
platform.machine(),
platform.platform(),
platform.uname(),
platform.version(),
platform.mac_ver(),
))

此脚本的输出运行在一些不同的系统(Linux, Windows, Solaris, MacOS)和架构(x86, x64, Itanium, power pc, sparc)上,可在这里获得:https://github.com/hpcugent/easybuild/wiki/OS_flavor_name_version

Ubuntu 12.04服务器为例给出:

Python version: ['2.6.5 (r265:79063, Oct  1 2012, 22:04:36) ', '[GCC 4.4.3]']
dist: ('Ubuntu', '10.04', 'lucid')
linux_distribution: ('Ubuntu', '10.04', 'lucid')
system: Linux
machine: x86_64
platform: Linux-2.6.32-32-server-x86_64-with-Ubuntu-10.04-lucid
uname: ('Linux', 'xxx', '2.6.32-32-server', '#62-Ubuntu SMP Wed Apr 20 22:07:43 UTC 2011', 'x86_64', '')
version: #62-Ubuntu SMP Wed Apr 20 22:07:43 UTC 2011
mac_ver: ('', ('', '', ''), '')