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

有帮助吗?

解决方案

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

的输出 platform.system() 如下:

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

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

其他提示

哎呀——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'

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

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

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

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

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

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

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

我这样做

import sys
print sys.platform

文档在这里: 系统平台.

您需要的所有内容可能都在 sys 模块中。

我使用的是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()

一个新的答案怎么样:

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

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

>>> import platform
>>> platform.system()

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

对于 Jython,我发现获取操作系统名称的唯一方法是检查 os.name Java 属性(尝试过 sys, osplatform WinXP 上的 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

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

Linux(64 位)+ WSL

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, ,其他一切保持不变
  • Windows Subsystem for Linux 上的输出相同(尝试使用 ubuntu 18.04 LTS),除了 platform.architecture() = ('64bit', 'ELF')

视窗(64 位)

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

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

Windows 8 上有趣的结果:

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

编辑: 那是一个 漏洞

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

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

同样的道理......

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

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

尝试这个:

import os

os.uname()

你可以做到:

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

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

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

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

如果您运行的是 macOS X 并运行 platform.system() 您会得到达尔文,因为MacOS X建在Apple的Darwin OS上。Darwin 是 macOS X 的内核,本质上是没有 GUI 的 macOS X。

该解决方案适用于两者 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()
import sys
import platform

# return a platform identifier
print(sys.platform)

# return system/os name
print(platform.system())

# print system info
# similar to 'uname' command in unix
print(platform.uname())

使用 import osos.name 关键词。

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

您可以查看以下代码 pyOSinfo 这是 点日期 包,以获取最相关的操作系统信息,如您的 Python 发行版所示。

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

enter image description here

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

我迟到了,但为了以防万一有人需要它,我用这个函数对我的代码进行调整,以便它可以在 Windows、Linux 和 MacO 上运行:

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'
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top