如何确定 Python 运行在哪个操作系统上

939
我需要查看哪些内容才能确定我是在Windows还是Unix等操作系统上?

4
详情请见(http://bugs.python.org/issue12326)。 - arnkore
7
这里有一个相关的问题:检查Linux发行版名称 - blong
27个回答

4

使用模块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

3

如果您正在运行 Mac OS X 并运行 platform.system(),则会得到 Darwin,因为 Mac OS X 是建立在苹果的 Darwin 操作系统上的。Darwin 是 Mac OS X 的内核,本质上是没有 GUI 的 Mac OS X。


3

这个解决方案适用于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()

2
使用以下简单的枚举实现即可。不需要外部库!
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。


2

有很多方法可以找到這個。最簡單的方法是使用 os 套件:

import os

print(os.name)

这个问题在14年前的第一个答案中已经被解决了,有什么新的进展吗? - Peter Mortensen

2
这是我用来调整代码以在Windows、Linux和macOS上运行的函数:
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'

2

您可以查看 pyOSinfo 代码,该代码是 pip-date 包的一部分,以获取最相关的操作系统信息,从您的 Python 发行版中看到。

人们想要检查其操作系统最常见的原因之一是终端兼容性和某些系统命令是否可用。不幸的是,此检查的成功在某种程度上取决于您的 Python 安装和操作系统。例如,uname 在大多数 Windows Python 包中不可用。上述 Python 程序将向您显示最常用的内置函数的输出,这些函数已由 os、sys、platform、site 提供。

Enter image description here

因此,获取仅包含必要代码的最佳方法是将那个作为示例。


请查看 *为什么在提问时不上传代码/错误的图片?(例如,"图片应该只用于说明无法以其他方式清晰表达的问题,例如提供用户界面的截图。"*)并做正确的事情(它也涵盖了答案)。提前致谢。 - Peter Mortensen

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接