808

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

4

26 回答 26

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

的输出platform.system()如下:

  • Linux:Linux
  • 苹果电脑:Darwin
  • 视窗:Windows

请参阅:platform— 访问底层平台的识别数据

于 2008-08-05T03:27:03.760 回答
202

Dang -- lbrandy 击败了我,但这并不意味着我不能为您提供 Vista 的系统结果!

>>> import os
>>> os.name
'nt'
>>> import platform
>>> platform.system()
'Windows'
>>> platform.release()
'Vista'

...而且我不敢相信还没有人为 Windows 10 发布过:

>>> import os
>>> os.name
'nt'
>>> import platform
>>> platform.system()
'Windows'
>>> platform.release()
'10'
于 2008-08-05T03:57:22.327 回答
140

作为记录,这是 Mac 上的结果:

>>> import os
>>> os.name
'posix'
>>> import platform
>>> platform.system()
'Darwin'
>>> platform.release()
'8.11.1'
于 2008-08-05T04:13:53.870 回答
107

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

import sys

if sys.platform.startswith("linux"):  # could be "linux", "linux2", "linux3", ...
    # linux
elif sys.platform == "darwin":
    # MAC OS X
elif sys.platform == "win32":
    # Windows (either 32-bit or 64-bit)
于 2014-09-16T07:42:41.593 回答
80

短篇故事

使用platform.system(). 它返回Windows,LinuxDarwin(对于 OSX)。

很长的故事

在 Python 中获取 OS 有 3 种方法,每种方法都有其优缺点:

方法一

>>> import sys
>>> sys.platform
'win32'  # could be 'linux', 'linux2, 'darwin', 'freebsd8' etc

这是如何工作的(来源):它在内部调用 OS API 来获取 OS 定义的 OS 名称。有关各种特定于操作系统的值,请参见此处

优点:没有魔法,低等级。

缺点:取决于操作系统版本,所以最好不要直接使用。

方法二

>>> import os
>>> os.name
'nt'  # for Linux and Mac it prints 'posix'

它是如何工作的(来源):它在内部检查 python 是否具有称为 posix 或 nt 的特定于操作系统的模块。

优点:简单检查 posix OS

缺点:Linux 或 OSX 之间没有区别。

方法三

>>> import platform
>>> platform.system()
'Windows' # for Linux it prints 'Linux', Mac it prints `'Darwin'

这是如何工作的(来源):在内部,它最终会调用内部操作系统 API,获取操作系统版本特定的名称,如“win32”或“win16”或“linux1”,然后标准化为更通用的名称,如“Windows”或“Linux”或'达尔文' 通过应用几种启发式方法。

Pro:Windows、OSX 和 Linux 的最佳便携方式。

缺点:Python 人员必须使规范化启发式保持最新。

概括

  • 如果您想检查操作系统是 Windows 还是 Linux 或 OSX,那么最可靠的方法是platform.system().
  • 如果您想通过内置 Python 模块进行特定于操作系统的调用,posix或者nt使用os.name.
  • 如果您想获取操作系统本身提供的原始操作系统名称,请使用sys.platform.
于 2019-09-23T23:28:46.173 回答
44

sys.platform如果您已经导入sys并且不想导入另一个模块,您也可以使用

>>> import sys
>>> sys.platform
'linux2'
于 2008-08-26T15:41:50.557 回答
36

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

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

您可以拨打以下几种不同的电话来确定您的位置

import platform
import sys

def linux_distribution():
  try:
    return platform.linux_distribution()
  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(platform.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: ('', ('', '', ''), '')
于 2013-01-23T10:55:26.150 回答
33

我开始更系统地列出使用各种模块可以期望的值(随意编辑和添加您的系统):

Linux(64 位)+ WSL

                            x86_64            aarch64
                            ------            -------
os.name                     posix             posix
sys.platform                linux             linux
platform.system()           Linux             Linux
sysconfig.get_platform()    linux-x86_64      linux-aarch64
platform.machine()          x86_64            aarch64
platform.architecture()     ('64bit', '')     ('64bit', 'ELF')
  • 尝试使用archlinux和mint,得到相同的结果
  • 在 python2sys.platform上以内核版本为后缀,例如linux2,其他一切都保持不变
  • Linux 的 Windows 子系统上的相同输出(尝试使用 ubuntu 18.04 LTS),除了platform.architecture() = ('64bit', 'ELF')

视窗(64 位)

(在 32bit 子系统中运行 32bit 列)

official python installer   64bit                     32bit
-------------------------   -----                     -----
os.name                     nt                        nt
sys.platform                win32                     win32
platform.system()           Windows                   Windows
sysconfig.get_platform()    win-amd64                 win32
platform.machine()          AMD64                     AMD64
platform.architecture()     ('64bit', 'WindowsPE')    ('64bit', 'WindowsPE')

msys2                       64bit                     32bit
-----                       -----                     -----
os.name                     posix                     posix
sys.platform                msys                      msys
platform.system()           MSYS_NT-10.0              MSYS_NT-10.0-WOW
sysconfig.get_platform()    msys-2.11.2-x86_64        msys-2.11.2-i686
platform.machine()          x86_64                    i686
platform.architecture()     ('64bit', 'WindowsPE')    ('32bit', 'WindowsPE')

msys2                       mingw-w64-x86_64-python3  mingw-w64-i686-python3
-----                       ------------------------  ----------------------
os.name                     nt                        nt
sys.platform                win32                     win32
platform.system()           Windows                   Windows
sysconfig.get_platform()    mingw                     mingw
platform.machine()          AMD64                     AMD64
platform.architecture()     ('64bit', 'WindowsPE')    ('32bit', 'WindowsPE')

cygwin                      64bit                     32bit
------                      -----                     -----
os.name                     posix                     posix
sys.platform                cygwin                    cygwin
platform.system()           CYGWIN_NT-10.0            CYGWIN_NT-10.0-WOW
sysconfig.get_platform()    cygwin-3.0.1-x86_64       cygwin-3.0.1-i686
platform.machine()          x86_64                    i686
platform.architecture()     ('64bit', 'WindowsPE')    ('32bit', 'WindowsPE')

一些备注:

  • 还有distutils.util.get_platform()与`sysconfig.get_platform相同
  • windows 上的 anaconda 与官方 python windows 安装程序相同
  • 我没有 Mac 也没有真正的 32 位系统,也没有动力在网上做

要与您的系统进行比较,只需运行此脚本(如果缺少,请在此处附加结果:)

from __future__ import print_function
import os
import sys
import platform
import sysconfig

print("os.name                      ",  os.name)
print("sys.platform                 ",  sys.platform)
print("platform.system()            ",  platform.system())
print("sysconfig.get_platform()     ",  sysconfig.get_platform())
print("platform.machine()           ",  platform.machine())
print("platform.architecture()      ",  platform.architecture())
于 2019-02-23T02:39:56.453 回答
17

一个新的答案怎么样:

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

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

于 2017-08-14T17:00:26.833 回答
11

我用的是weblogic自带的WLST工具,并没有实现平台包。

wls:/offline> import os
wls:/offline> print os.name
java 
wls:/offline> import sys
wls:/offline> print sys.platform
'java1.5.0_11'

除了修补系统javaos.py在带有 jdk1.5 的 windows 2003 上出现 os.system() 问题)(我不能这样做,我必须使用开箱即用的 weblogic),这就是我使用的:

def iswindows():
  os = java.lang.System.getProperty( "os.name" )
  return "win" in os.lower()
于 2010-06-11T07:37:56.837 回答
11

使用platform.system()

返回系统/操作系统名称,例如“Linux”、“Darwin”、“Java”、“Windows”。如果无法确定值,则返回空字符串。

import platform
system = platform.system().lower()

is_windows = system == 'windows'
is_linux = system == 'linux'
is_mac = system == 'darwin'
于 2020-10-20T12:03:31.183 回答
8

/usr/bin/python3.2

def cls():
    from subprocess import call
    from platform import system

    os = system()
    if os == 'Linux':
        call('clear', shell = True)
    elif os == 'Windows':
        call('cls', shell = True)
于 2011-10-10T00:11:15.410 回答
8

对于 Jython,我发现获取操作系统名称的唯一方法是检查os.nameJava 属性(在 WinXP 上尝试使用sys,osplatformJython 2.5.3 的模块):

def get_os_platform():
    """return platform name, but for Jython it uses os.name Java property"""
    ver = sys.platform.lower()
    if ver.startswith('java'):
        import java.lang
        ver = java.lang.System.getProperty("os.name").lower()
    print('platform: %s' % (ver))
    return ver
于 2013-01-09T08:47:48.920 回答
7

Windows 8 上的有趣结果:

>>> import os
>>> os.name
'nt'
>>> import platform
>>> platform.system()
'Windows'
>>> platform.release()
'post2008Server'

编辑:这是一个错误

于 2013-02-14T22:44:56.070 回答
7

如果您在 Windows 上使用 Cygwin,请注意 where os.nameis posix.

>>> import os, platform
>>> print os.name
posix
>>> print platform.system()
CYGWIN_NT-6.3-WOW
于 2015-07-08T14:46:49.300 回答
7

我知道这是一个老问题,但我相信我的回答可能对一些正在寻找一种简单易懂的 Python 方法来检测代码中操作系统的人有所帮助。在python3.7上测试

from sys import platform


class UnsupportedPlatform(Exception):
    pass


if "linux" in platform:
    print("linux")
elif "darwin" in platform:
    print("mac")
elif "win" in platform:
    print("windows")
else:
    raise UnsupportedPlatform
于 2020-01-22T15:30:51.670 回答
5

如果您不是在寻找内核版本等,而是在寻找 linux 发行版,您可能需要使用以下内容

在python2.6+

>>> import platform
>>> print platform.linux_distribution()
('CentOS Linux', '6.0', 'Final')
>>> print platform.linux_distribution()[0]
CentOS Linux
>>> print platform.linux_distribution()[1]
6.0

在python2.4

>>> import platform
>>> print platform.dist()
('centos', '6.0', 'Final')
>>> print platform.dist()[0]
centos
>>> print platform.dist()[1]
6.0

显然,这只有在你在 linux 上运行时才有效。如果您想跨平台拥有更多通用脚本,可以将其与其他答案中给出的代码示例混合使用。

于 2013-03-28T05:19:17.007 回答
5

试试这个:

import os

os.uname()

你可以做到:

info=os.uname()
info[0]
info[1]
于 2015-01-16T18:13:11.747 回答
4

您也可以只使用平台模块而不导入 os 模块来获取所有信息。

>>> import platform
>>> platform.os.name
'posix'
>>> platform.uname()
('Darwin', 'mainframe.local', '15.3.0', 'Darwin Kernel Version 15.3.0: Thu Dec 10 18:40:58 PST 2015; root:xnu-3248.30.4~1/RELEASE_X86_64', 'x86_64', 'i386')

使用此行可以实现用于报告目的的漂亮整洁的布局:

for i in zip(['system','node','release','version','machine','processor'],platform.uname()):print i[0],':',i[1]

这给出了这个输出:

system : Darwin
node : mainframe.local
release : 15.3.0
version : Darwin Kernel Version 15.3.0: Thu Dec 10 18:40:58 PST 2015; root:xnu-3248.30.4~1/RELEASE_X86_64
machine : x86_64
processor : i386

通常缺少的是操作系统版本,但您应该知道您运行的是 windows、linux 还是 mac,平台独立的方法是使用此测试:

In []: for i in [platform.linux_distribution(),platform.mac_ver(),platform.win32_ver()]:
   ....:     if i[0]:
   ....:         print 'Version: ',i[0]
于 2016-08-20T08:03:03.770 回答
3

同理....

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")
于 2011-09-28T17:54:43.230 回答
3

使用模块平台检查可用的测试并为您的系统打印答案:

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
于 2014-10-30T00:43:08.447 回答
2

如果您正在运行 macOS X 并运行platform.system(),您将获得 darwin,因为 macOS X 是基于 Apple 的 Darwin OS 构建的。Darwin 是 macOS X 的内核,本质上是没有 GUI 的 macOS X。

于 2018-01-13T21:29:45.910 回答
2

此解决方案适用于pythonjython

模块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()
于 2019-01-29T13:06:52.727 回答
1

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

PS是python3

于 2018-09-27T17:39:31.423 回答
1

您可以查看pip-datepyOSinfo包中的代码,以获取最相关的操作系统信息,如您的 Python 发行版所示。

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

在此处输入图像描述

因此,仅获取基本代码的最佳方法是将作为示例。(我想我可以把它贴在这里,但这在政治上是不正确的。)

于 2019-02-07T21:10:29.867 回答
1

我迟到了,但是,以防万一有人需要它,我用这个函数对我的代码进行调整,以便它在 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'
于 2019-05-22T13:32:36.843 回答