【问题标题】:Python: What OS am I running on?Python:我在什么操作系统上运行?
【发布时间】:2010-09-05 08:04:23
【问题描述】:

我需要查看哪些内容才能确定我使用的是 Windows 还是 Unix 等?

【问题讨论】:

标签: python cross-platform platform-specific platform-agnostic


【解决方案1】:
>>> import os
>>> os.name
'posix'
>>> import platform
>>> platform.system()
'Linux'
>>> platform.release()
'2.6.22-15-generic'

platform.system()的输出如下:

  • Linux:Linux
  • 苹果机:Darwin
  • Windows:Windows

见:platform — Access to underlying platform’s identifying data

【讨论】:

  • 为什么我应该更喜欢platform 而不是sys.platform
  • @matth 输出更加一致。即platform.system() 返回"Windows" 而不是"win32"sys.platform 在旧版本的 Python 上还包含 "linux2",而在新版本上只包含 "linux"platform.system() 总是只返回 "Linux"
  • 在 mac os X 上,platform.system() 总是返回“Darwin”?还是有其他可能的情况?
  • @baptistechéné,我知道你问这件事已经一年多了,但作为评论不会有什么坏处,我还是会发布它:) 所以,它背后的原因是因为它显示了内核名称。同样,Linux(内核)发行版有许多名称(Ubuntu、Arch、Fedora 等),但它会以内核名称 Linux 的形式出现。 Darwin(基于 BSD 的内核)有它的周边系统 macOS。我很确定苹果确实将 Darwin 作为开源代码发布,但据我所知,没有其他发行版在 Darwin 上运行。
  • @TooroSan os.uname() 仅适用于 Unix 系统。 Python 3 文档:docs.python.org/3/library/os.htmlAvailability: recent flavors of Unix.
【解决方案2】:

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'

【讨论】:

  • Windows 7:platform.release()'7'
  • 所以,是的,我刚刚在我的 Windows 10 上运行了platform.release(),它肯定只是给了我'8'。也许我在升级之前安装了 python,但真的吗??
  • 我认为您更有可能从 Windows 8 升级(而不是全新安装)以及 Python 在注册表中查找的任何内容或遗留的任何内容?
  • Windows 上的 Python 版本查找似乎在其核心使用 Win32 api 函数 GetVersionEx。这篇 Microsoft 文章顶部关于该功能的注释可能是相关的:msdn.microsoft.com/en-us/library/windows/desktop/…
【解决方案3】:

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

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

【讨论】:

【解决方案4】:

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

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

【讨论】:

  • 这个示例代码来自任何 python 模块吗?这是实际上回答问题的唯一答案。
  • 对于更模糊的结果,``_platform.startswith('linux')
  • sys.platform == 'cygwin' 在 Windows Cygwin shell 上
  • 小问题:win64 不存在:github.com/python/cpython/blob/master/Lib/platform.py。所有 Windows 版本均为win32
  • 在我的 windows64 sys.platform 中返回 win32
【解决方案5】:

短篇小说

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

长篇大论

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

方法一

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

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

专业人士:没有魔法,低级。

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

方法二

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

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

专业版:检查 posix 操作系统是否简单

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

方法3

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

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

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

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

总结

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

【讨论】:

  • “应该有一种(最好只有一种)做事的方式”。但是我相信这是正确的答案。您需要与标题操作系统名称进行比较,但这不是这样的问题,并且更便携。
【解决方案6】:

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

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

【讨论】:

  • 除了必须或不导入另一个模块之外,这些方法是否有任何优势?
  • 作用域是主要优势。您需要尽可能少的全局变量名。如果您已经将“sys”作为全局名称,则不应再添加一个。但如果你还没有使用“sys”,使用“_platform”可能更具描述性,不太可能与其他含义发生冲突。
【解决方案7】:

如果您想要用户可读的数据但仍然很详细,您可以使用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: ('', ('', '', ''), '')

【讨论】:

  • DeprecationWarning: dist() and linux_distribution() functions are deprecated in Python 3.5
【解决方案8】:

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

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试过,结果一样
  • 在python2上sys.platform以内核版本为后缀,例如linux2,其他一切都保持不变
  • 在适用于 Linux 的 Windows 子系统上的输出相同(使用 ubuntu 18.04 LTS 进行了尝试),platform.architecture() = ('64bit', 'ELF') 除外

WINDOWS(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 相同
  • anaconda on 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
【解决方案9】:

来个新答案怎么样:

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

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

【讨论】:

  • psutil 不是标准库的一部分
【解决方案10】:

我使用的是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 (issue with os.system() on windows 2003 with jdk1.5)(这个我做不到,我必须使用开箱即用的weblogic),这是我用的:

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

【讨论】:

    【解决方案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'
    

    【讨论】:

    • 如何获取我的发行版的名称?例如,如果我在运行 Arch,我如何获得 Arch
    【解决方案12】:

    /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)
    

    【讨论】:

    • 欢迎您,在这里,解释为什么要使用您的解决方案而不只是如何使用是一个很好的做法。这将使您的答案更有价值,并帮助进一步的读者更好地理解您是如何做到的。我还建议您查看我们的常见问题解答:stackoverflow.com/faq
    • 很好的答案,甚至可能与原始答案相当。但你可以解释原因。
    【解决方案13】:

    对于 Jython,我找到的获取操作系统名称的唯一方法是检查 os.name Java 属性(在 WinXP 上使用 sysosplatform 模块尝试 Jython 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
    

    【讨论】:

    • 您也可以调用“platform.java_ver()”来提取Jython中的操作系统信息。
    【解决方案14】:

    Windows 8 上的有趣结果:

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

    编辑:这是bug

    【讨论】:

      【解决方案15】:

      注意你是否在 Windows 上使用 Cygwin,其中 os.nameposix

      >>> import os, platform
      >>> print os.name
      posix
      >>> print platform.system()
      CYGWIN_NT-6.3-WOW
      

      【讨论】:

        【解决方案16】:

        我知道这是一个老问题,但我相信我的回答可能对一些正在寻找一种简单易懂的 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
        

        【讨论】:

        • 如果此代码曾被不了解 if 结构的人重构,这可能会导致错误检测到 macos,因为 win 包含在 darwin 中。 startswidth 问题较少。
        • 如果你正在重构代码并且你还没有掌握 If 语句,你可能有更大的鱼要炸。
        • 如果可能,更改 if 分支不应导致误报。这个概念被称为干净的代码。
        【解决方案17】:

        如果您不是在寻找内核版本等,而是在寻找 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 上运行时才有效。如果您想跨平台拥有更通用的脚本,可以将其与其他答案中给出的代码示例混合使用。

        【讨论】:

          【解决方案18】:

          试试这个:

          import os
          
          os.uname()
          

          你可以做到的:

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

          【讨论】:

          【解决方案19】:

          您也可以只使用平台模块而不导入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]
          

          【讨论】:

            【解决方案20】:

            同理....

            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")
            

            【讨论】:

            • 如果您在 Mac 上,这是有问题的,因为 platform.system() 在 Mac 上返回 "Darwin" 并且 "Darwin".lower().find("win") = 3。跨度>
            • is_windows = platform.system().lower().startswith("win") 或 False
            【解决方案21】:

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

            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
            

            【讨论】:

              【解决方案22】:

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

              【讨论】:

                【解决方案23】:

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

                【讨论】:

                  【解决方案24】:

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

                  P.S 是python3

                  【讨论】:

                    【解决方案25】:

                    您可以查看 pip-date 包中的 pyOSinfo 中的代码,以获取最相关的操作系统信息,如您的 Python 所见分配。

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

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

                    【讨论】:

                      【解决方案26】:

                      我迟到了,但是,以防万一有人需要它,我用这个函数来调整我的代码,使其在 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'
                      

                      【讨论】:

                        猜你喜欢
                        • 2012-05-21
                        • 1970-01-01
                        • 1970-01-01
                        • 1970-01-01
                        • 2011-06-01
                        • 1970-01-01
                        相关资源
                        最近更新 更多