我需要查看哪些内容才能确定我是在Windows还是Unix等操作系统上?
使用模块platform检查可用的测试,并将答案打印出来:
import platform
print dir(platform)
for x in dir(platform):
if x[0].isalnum():
try:
result = getattr(platform, x)()
print "platform." + x + ": " + result
except TypeError:
continue
如果您正在运行 Mac OS X 并运行 platform.system()
,则会得到 Darwin,因为 Mac OS X 是建立在苹果的 Darwin 操作系统上的。Darwin 是 Mac OS X 的内核,本质上是没有 GUI 的 Mac OS X。
这个解决方案适用于Python和Jython。
模块os_identify.py:
import platform
import os
# This module contains functions to determine the basic type of
# OS we are running on.
# Contrary to the functions in the `os` and `platform` modules,
# these allow to identify the actual basic OS,
# no matter whether running on the `python` or `jython` interpreter.
def is_linux():
try:
platform.linux_distribution()
return True
except:
return False
def is_windows():
try:
platform.win32_ver()
return True
except:
return False
def is_mac():
try:
platform.mac_ver()
return True
except:
return False
def name():
if is_linux():
return "Linux"
elif is_windows():
return "Windows"
elif is_mac():
return "Mac"
else:
return "<unknown>"
使用方法如下:
import os_identify
print "My OS: " + os_identify.name()
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 tested this one
你可以通过枚举值简单地访问它们:
if OS.LINUX.value:
print("Cool. It is Linux")
注意:这是Python 3。
有很多方法可以找到這個。最簡單的方法是使用 os 套件:
import os
print(os.name)
import sys
def get_os(osoptions={'linux':'linux', 'Windows':'win', 'macos':'darwin'}):
'''
Get OS to allow code specifics
'''
opsys = [k for k in osoptions.keys() if sys.platform.lower().find(osoptions[k].lower()) != -1]
try:
return opsys[0]
except:
return 'unknown_OS'
您可以查看 pyOSinfo
代码,该代码是 pip-date 包的一部分,以获取最相关的操作系统信息,从您的 Python 发行版中看到。
人们想要检查其操作系统最常见的原因之一是终端兼容性和某些系统命令是否可用。不幸的是,此检查的成功在某种程度上取决于您的 Python 安装和操作系统。例如,uname
在大多数 Windows Python 包中不可用。上述 Python 程序将向您显示最常用的内置函数的输出,这些函数已由 os、sys、platform、site
提供。
因此,获取仅包含必要代码的最佳方法是将那个作为示例。