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

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

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

1245

61
为什么我应该优先选择 platform 而不是 sys.platform - matth
86
稍微更加一致的输出。例如,platform.system() 返回 "Windows" 而不是 "win32"。在旧版本的 Python 中,sys.platform 还包含 "linux2",而在较新的版本中则只包含 "linux"。而 platform.system() 始终只返回 "Linux" - erb
11
在Mac OS X系统中,platform.system()始终返回"Darwin"吗?还是还有其他可能情况? - baptiste chéné
9
@baptistechéné,我知道你提问已经超过一年了,但是留下评论也无妨,我还是会回复 :)这个问题的原因是因为它展示了内核名字。就像Linux(内核)发行版有很多名称(例如Ubuntu、Arch、Fedora等),但它会呈现自己的内核名称Linux一样。Darwin(一个基于BSD的内核)有其周围的系统macOS。我相信苹果已经开放了Darwin的源代码,但我不知道有没有其他运行在Darwin上的发行版。 - Joao Paulo Rabelo
4
@TooroSan os.uname() 只存在于 Unix 系统中。Python 3 文档链接如下: https://docs.python.org/3/library/os.html 可用性:最近的 Unix 系统。 - Irving Moy
显示剩余5条评论

218

以下是Windows 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'

9
Windows 7: platform.release()的翻译是'7' - Hugo
5
是的,我刚在我的Windows 10上运行了platform.release(),结果显示为“'8'”。也许是因为我在升级系统前就已经安装了Python,但是这样真的没问题吗? - Codesmith
4
我原以为你更可能是从Windows 8升级的(而不是进行了全新安装),并且Python在注册表或其他地方查找时留下了一些残留物? - OJFord
7
Python在Windows上的版本查询似乎核心使用了Win32 API函数GetVersionEx。该Microsoft文章顶部的注释与该函数有关,可能会相关:https://msdn.microsoft.com/en-us/library/windows/desktop/ms724451(v=vs.85).aspx - theferrit32

148

仅供参考,以下是在 Mac 上的结果:

>>> import os
>>> os.name
'posix'
>>> import platform
>>> platform.system()
'Darwin'
>>> platform.release()
'8.11.1'

4
在 macOS Catalina 10.15.2 上,platform.release() 返回 '19.2.0' - user3064538
2
“19.2.0”是随Catalina 10.15.2一起发布的Darwin版本号:https://en.wikipedia.org/wiki/MacOS_Catalina#Release_history - philshem

124

短故事

使用 platform.system()。它会返回 WindowsLinuxDarwin(用于 OS X)。

长故事

在 Python 中获取操作系统有三种方法,每种方法都有其优缺点:

方法 1

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

这是如何工作的(source):它在内部调用操作系统API来获取由操作系统定义的操作系统名称。请参见here以获取各种特定于操作系统的值。

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

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

方法2

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

这是如何工作的(source):内部检查Python是否具有名为posixnt的特定于操作系统的模块。

优点:简单检查是否为POSIX操作系统

缺点:无法区分Linux或OS X。

方法3

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

这是如何运作的(source):内部最终会调用操作系统API,获取操作系统特定版本名称,例如“win32”或“win16”或“linux1”,然后通过应用多个启发式算法来规范化为更通用的名称,例如“Windows”或“Linux”或“Darwin”。

优点:适用于Windows、OS X和Linux的最佳可移植方式。

缺点:Python开发者必须保持规范化启发式算法的最新状态。

摘要

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

8
“有且只有一种方法来做事情”这个说法就到此为止。然而,我认为这是正确的答案。你需要与已命名的操作系统名称进行比较,但这并不是什么问题,而且会更具可移植性。 - vincent-lg
1
请注意,在Python 3.10中,如果os.uname抛出异常,则platform.system默认为sys.platform:https://github.com/python/cpython/blob/a6c3f6d34792c5f9dc296ce8329938b7b2b02ea9/Lib/platform.py#L830-L833 - Heberto Mayorquin

119

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

import sys

if sys.platform.startswith("linux"):  # could be "linux", "linux2", "linux3", ...
    # linux
elif sys.platform == "darwin":
    # MAC OS X
elif os.name == "nt":
    # Windows, Cygwin, etc. (either 32-bit or 64-bit)

10
为了获得更模糊的结果,请使用“_platform.startswith('linux')”。 - Klaatu von Schlacker
4
在Windows Cygwin shell中,sys.platform == 'cygwin' - Ed Randall
8
小问题:win64 不存在:https://github.com/python/cpython/blob/master/Lib/platform.py。所有 Windows 版本都是 win32 - user136036
2
在我的 Windows64 系统中,sys.platform 返回 win32。 - Badr Elmers

59

我开始更系统地列出了使用各种模块可以期望的值:

Linux(64位)+ {{link1: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')

Windows(64位)

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

Official Python installer   64 bit                    32 bit
-------------------------   -----                     -----
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                       64 bit                     32 bit
-----                       -----                     -----
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                      64 bit                    32 bit
------                      -----                     -----
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`相同
  • Anaconda在Windows上与官方的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())

在最新的MSYS2上,MinGW64报告sys.platformwin32,就像你所报告的那样,但是MSYS2和UCRT64报告cygwin而不是msys - Paebbels

45

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

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

除了需要或不需要导入另一个模块之外,这些方法中是否有任何优势? - matth
作用域是主要的优势。您希望尽可能少地使用全局变量名称。当您已经有“sys”作为全局名称时,不应再添加另一个名称。但是,如果您尚未使用“sys”,则使用“_platform”可能更具描述性,且不太可能与其他含义冲突。 - sanderd17

43

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

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

以下是几个不同的可能调用,可以用来确定您所在的位置。linux_distributiondist在最近的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、ItaniumPowerPCSPARC)上运行,并且可以在 OS_flavor_name_version 上获取。

例如,Ubuntu 12.04 服务器(Precise Pangolin)会给出:

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: ('', ('', '', ''), '')

2
DeprecationWarning: dist() and linux_distribution() functions are deprecated in Python 3.5 - user3064538

19

使用:

import psutil

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

如果我使用的是 macOS,那么这将是输出结果。


12
psutil不是Python标准库的一部分。 - Corey Goldberg

16

使用platform.system()

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

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

is_windows = system == 'windows'
is_linux = system == 'linux'
is_mac = system == 'darwin'

我怎样才能获取我的发行版名称?例如,如果我正在运行Arch,我怎样能获取 Arch - dio

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