如何识别 Python 运行在哪个操作系统上

2024-12-11 08:48:00
admin
原创
163
摘要:问题描述:我需要查看什么才能知道我使用的是 Windows 还是 Unix 等等?解决方案 1:>>> import os >>> os.name 'posix' >>> import platform >>> platform.s...

问题描述:

我需要查看什么才能知道我使用的是 Windows 还是 Unix 等等?


解决方案 1:

>>> import os

>>> os.name
'posix'

>>> import platform

>>> platform.system()
'Linux'

>>> platform.release()
'2.6.22-15-generic'

的输出platform.system()如下:

  • Linux:Linux

  • 苹果:Darwin

  • 视窗:Windows

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

解决方案 2:

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

解决方案 3:

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

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

解决方案 4:

短篇小说

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

长话短说

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

方法 1

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

工作原理(来源):它在内部调用操作系统 API 来获取操作系统定义的操作系统名称。请参阅此处了解各种特定于操作系统的值。

优点:没有魔法,水平低。

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

方法 2

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

工作原理(来源):内部检查 Python 是否具有名为posixnt 的操作系统特定模块。

优点:轻松检查是否为POSIX操作系统

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

方法 3

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

其工作原理(来源):在内部,它最终将调用内部操作系统 API,获取特定于操作系统版本的名称,如“win32”或“win16”或“linux1”,然后通过应用几种启发式方法将其规范化为更通用的名称,如“Windows”或“Linux”或“Darwin”。

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

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

概括

  • 如果您想检查操作系统是 Windows 还是 Linux,或者是 OS X,那么最可靠的方法是platform.system()

  • 如果您想进行特定于操作系统的调用,但通过内置的 Python 模块posixnt,则使用os.name

  • 如果您想获取操作系统本身提供的原始操作系统名称,请使用sys.platform

解决方案 5:

使用 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)

解决方案 6:

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

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')
  • 我尝试使用Arch Linux和Linux Mint,但得到了相同的结果

  • 在 Python 2 上,sys.platform以内核版本作为后缀,例如linux2,其他所有内容保持不变

  • Windows Subsystem for Linux上的输出相同(我尝试使用Ubuntu 18.04 (Bionic Beaver) LTS),除了platform.architecture() = ('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”相同的

  • 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())

解决方案 7:

sys.platform如果你已经导入了sys,但不想再导入其他模块,也可以使用

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

解决方案 8:

如果您想要用户可读的数据,但仍需要详细信息,则可以使用platform.platform():

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

您可以进行以下几种不同的调用来识别您所在的位置。linux_distribution和dist在最近的 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('
'),
str(dist()),
linux_distribution(),
platform.system(),
platform.machine(),
platform.platform(),
platform.uname(),
platform.version(),
platform.mac_ver(),
))

该脚本的输出可以在几个不同的系统 (Linux、Windows、Solaris 和 macOS) 和体系结构 (x86、x64、Itanium、PowerPC和SPARC ) 上运行,可在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: ('', ('', '', ''), '')

解决方案 9:

使用:

import psutil

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

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

解决方案 10:

使用platform.system()

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

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

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

解决方案 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(在装有 JDK 1.5 的 Windows Server 2003 上存在 os.system() 问题)(我做不到,我必须使用开箱即用的 WebLogic)之外,我还使用以下方法:

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

解决方案 12:

对于Jython来说,获取我找到的操作系统名称的唯一方法是检查os.nameJava 属性(我尝试使用sysos以及Windows XPplatform上 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

解决方案 13:

如果你在 Windows 上使用 Cygwin 的话请注意,其中os.nameposix

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

解决方案 14:

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

解决方案 15:

Windows 8上的有趣结果:

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

这是一个错误。

解决方案 16:

这是一种简单易懂的 Python 代码检测操作系统的方法。已在 Python 3.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

解决方案 17:

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

在 Python 2.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

在 Python 2.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:

您还可以仅使用平台模块而不导入操作系统模块来获取所有信息。

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

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

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

解决方案 23:

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

解决方案 24:

使用如下所示的简单枚举实现。无需任何外部库!

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

PS:是Python3。

解决方案 25:

有很多方法可以找到它。最简单的方法是使用os包:

import os

print(os.name)

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

解决方案 27:

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

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

在此处输入图片描述

因此,获取必要代码的最佳方式就是将作为示例。

解决方案 28:

如果要使用与操作系统相关的操作。 你可以使用以下代码:

import sys


def getOS() -> str:
    os = sys.platform
    if os == "linux":
        return "linux"
    elif os == "darwin":
        return "mac"
    elif os == "win32":
        return "windows"
    else:
        raise Exception("OS not supported")

有关更多详细信息,请参阅此参考:https ://docs.python.org/3/library/sys.html#sys.platform

相关推荐
  政府信创国产化的10大政策解读一、信创国产化的背景与意义信创国产化,即信息技术应用创新国产化,是当前中国信息技术领域的一个重要发展方向。其核心在于通过自主研发和创新,实现信息技术应用的自主可控,减少对外部技术的依赖,并规避潜在的技术制裁和风险。随着全球信息技术竞争的加剧,以及某些国家对中国在科技领域的打压,信创国产化显...
工程项目管理   1989  
  为什么项目管理通常仍然耗时且低效?您是否还在反复更新电子表格、淹没在便利贴中并参加每周更新会议?这确实是耗费时间和精力。借助软件工具的帮助,您可以一目了然地全面了解您的项目。如今,国内外有足够多优秀的项目管理软件可以帮助您掌控每个项目。什么是项目管理软件?项目管理软件是广泛行业用于项目规划、资源分配和调度的软件。它使项...
项目管理软件   1446  
  在当今快速发展的IT行业中,项目管理工具的选择对于项目的成功至关重要。随着技术的不断进步,项目经理们需要更加高效、灵活的工具来应对复杂的项目需求。本文将介绍2025年IT项目经理力推的10款管理工具,帮助您在项目管理中取得更好的成果。信创国产项目管理软件 - 禅道禅道是一款国产开源的项目管理软件,禅道开源版不限人数,功...
项目管理工具   0  
  在当今快速变化的商业环境中,项目管理软件已成为企业提升效率、优化资源分配和确保项目成功的关键工具。随着技术的不断进步,市场上涌现出众多功能各异的项目管理工具,每一款都有其独特的优势和适用场景。本文将深入评测2025年最受欢迎的10款项目管理软件,帮助您根据自身需求做出明智的选择。信创国产项目管理软件 - 禅道禅道是一款...
项目管理平台   2  
  产品开发效率对于企业的竞争力至关重要。在当今复杂多变的商业环境中,如何有效提升产品开发效率成为众多企业关注的焦点。产品生命周期管理(PLM)作为一种整合产品全生命周期信息的管理理念和技术,为提升产品开发效率提供了有力的支持。通过合理运用PLM,企业能够优化流程、加强协作、提高数据管理水平,从而实现产品开发的高效运作。接...
plm开发流程软件   3  
热门文章
项目管理软件有哪些?
云禅道AD
禅道项目管理软件

云端的项目管理软件

尊享禅道项目软件收费版功能

无需维护,随时随地协同办公

内置subversion和git源码管理

每天备份,随时转为私有部署

免费试用