关于跨平台:Python:我正在运行什么操作系统?

Python: What OS am I running on?

我要查看我是在Windows还是Unix等上,我需要查看什么?


1
2
3
4
5
6
7
8
>>> import os
>>> os.name
'posix'
>>> import platform
>>> platform.system()
'Linux'
>>> platform.release()
'2.6.22-15-generic'

platform.system()的输出如下:

  • Linux:Linux
  • Mac:Darwin
  • Windows:Windows

请参阅:platform-访问基础平台的标识数据


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

1
2
3
4
5
6
7
8
>>> import os
>>> os.name
'nt'
>>> import platform
>>> platform.system()
'Windows'
>>> platform.release()
'Vista'

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

1
2
3
4
5
6
7
8
>>> import os
>>> os.name
'nt'
>>> import platform
>>> platform.system()
'Windows'
>>> platform.release()
'10'


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

1
2
3
4
5
6
7
8
>>> import os
>>> os.name
'posix'
>>> import platform
>>> platform.system()
'Darwin'
>>> platform.release()
'8.11.1'


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

1
2
3
4
5
6
7
8
9
10
from sys import platform as _platform

if _platform =="linux" or _platform =="linux2":
    # linux
elif _platform =="darwin":
    # MAC OS X
elif _platform =="win32":
    # Windows
elif _platform =="win64":
    # Windows 64-bit


如果您已经导入了sys并且不想导入其他模块,则也可以使用sys.platform

1
2
3
>>> import sys
>>> sys.platform
'linux2'


如果您希望用户可读的数据但仍然详细,则可以使用platform.platform()

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

您可以拨打以下几种可能的电话来识别自己的位置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
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('\
'
),
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服务器为例:

1
2
3
4
5
6
7
8
9
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: ('', ('', '', ''), '')


短篇故事

使用platform.system()。它返回WindowsLinuxDarwin(对于OSX)。

很长的故事

使用Python获取OS的方法有3种,每种方法各有优缺点:

方法1

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

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

优点:无魔法,低等级。

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

方法2

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

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

专业版:易于检查posix OS

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

方法3

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

工作原理(来源):内部将最终调用内部OS API,获取特定于操作系统版本的名称,例如" win32"或" win16"或" linux1",然后将其标准化为更通用的名称,例如" Windows"或" Linux"或通过应用几种启发式方法来"达尔文"。

专业版:Windows,OSX和Linux的最佳便携式方式。

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

概要

  • 如果要检查OS是Windows还是Linux或OSX,则最可靠的方法是platform.system()
  • 如果要通过内置Python模块posixnt进行特定于操作系统的调用,请使用os.name
  • 如果要获取OS本身提供的原始OS名称,请使用sys.platform


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

Linux(64位)+ WSL

1
2
3
4
5
6
os.name                     posix
sys.platform                linux
platform.system()           Linux
sysconfig.get_platform()    linux-x86_64
platform.machine()          x86_64
platform.architecture()     ('64bit', '')
  • 尝试使用archlinux和mint,得到相同的结果
  • 在python2 sys.platform上的内核版本带有后缀,例如 linux2,其他所有内容保持不变
  • 在Linux的Windows子系统上,输出与platform.architecture() = ('64bit', 'ELF')相同,但已与ubuntu 18.04 LTS进行了尝试。

WINDOWS(64位)

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
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位系统,也没有动力在线进行此操作

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

1
2
3
4
5
6
7
8
9
10
11
12
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())

新答案如何:

1
2
3
4
import psutil
psutil.MACOS   #True (OSX is deprecated)
psutil.WINDOWS #False
psutil.LINUX   #False

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


我使用的是weblogic随附的WLST工具,它没有实现平台软件包。

1
2
3
4
5
6
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(在Windows 2003上使用jdk1.5在os.system()上发布)(我不能这样做,我必须开箱即用使用weblogic)之外,这是我使用的方法:

1
2
3
def iswindows():
  os = java.lang.System.getProperty("os.name" )
  return"win" in os.lower()

对于Jython,我发现获得操作系统名称的唯一方法是检查os.name Java属性(在WinXP上针对Jython 2.5.3尝试了sysosplatform模块):

1
2
3
4
5
6
7
8
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


/usr/bin/python3.2

1
2
3
4
5
6
7
8
9
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)


在Windows 8上有趣的结果:

1
2
3
4
5
6
7
8
>>> import os
>>> os.name
'nt'
>>> import platform
>>> platform.system()
'Windows'
>>> platform.release()
'post2008Server'

编辑:那是一个错误


请注意,如果您使用的Windows是Cygwin,其中os.nameposix

1
2
3
4
5
>>> import os, platform
>>> print os.name
posix
>>> print platform.system()
CYGWIN_NT-6.3-WOW

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

在python2.6 +中

1
2
3
4
5
6
7
>>> 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中

1
2
3
4
5
6
7
>>> import platform
>>> print platform.dist()
('centos', '6.0', 'Final')
>>> print platform.dist()[0]
centos
>>> print platform.dist()[1]
6.0

显然,仅当您在linux上运行此命令时,此命令才有效。 如果希望跨平台使用更通用的脚本,可以将其与其他答案中给出的代码示例混合使用。


以同样的方式...

1
2
3
4
5
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")


尝试这个:

1
2
3
import os

os.uname()

你可以做到:

1
2
3
info=os.uname()
info[0]
info[1]


我知道这是一个古老的问题,但我相信我的回答可能对某些正在寻找一种简单,易于理解的python方法在其代码中检测OS的人有所帮助。 在python3.7上测试

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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

您也可以仅使用平台模块,而无需导入os模块来获取所有信息。

1
2
3
4
5
>>> 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')

使用此行可以实现一个美观,整洁的报表布局:

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

给出以下输出:

1
2
3
4
5
6
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,平台独立的方式是使用此测试:

1
2
3
In []: for i in [platform.linux_distribution(),platform.mac_ver(),platform.win32_ver()]:
   ....:     if i[0]:
   ....:         print 'Version: ',i[0]

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

1
2
3
4
5
6
7
8
9
10
11
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

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


此解决方案适用于pythonjython

模块os_identify.py:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
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>"

像这样使用:

1
2
3
import os_identify

print"My OS:" + os_identify.name()

像下面这样的简单Enum实现如何? 无需外部库!

1
2
3
4
5
6
7
8
9
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值进行访问

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

P.S是python3


您可以查看pip-date软件包中pyOSinfo中的代码,以获取最相关的操作系统信息,如从Python发行版中所见。

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

enter image description here

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


我迟到了游戏,但是,以防万一有人需要它,我可以使用此功能对代码进行调整,使其可以在Windows,Linux和MacO上运行:

1
2
3
4
5
6
7
8
9
10
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'