Python:我运行的是什么操作系统?

Python:我运行的是什么操作系统?,python,cross-platform,platform-specific,platform-agnostic,Python,Cross Platform,Platform Specific,Platform Agnostic,我需要看什么才能知道我是在Windows上还是在Unix上,等等 >>> import os >>> os.name 'posix' >>> import platform >>> platform.system() 'Linux' >>> platform.release() '2.6.22-15-generic' 其结果如下: Linux:Linux 麦克:Darwin 窗口:Windows 请参

我需要看什么才能知道我是在Windows上还是在Unix上,等等

>>> import os
>>> os.name
'posix'
>>> import platform
>>> platform.system()
'Linux'
>>> platform.release()
'2.6.22-15-generic'
其结果如下:

  • Linux:
    Linux
  • 麦克:
    Darwin
  • 窗口:
    Windows
请参阅:

当--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'
如果您已经导入了
sys
,并且不想导入其他模块,也可以使用

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

我使用的是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()(我不能这么做,我必须使用现成的weblogic),我使用的是:

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

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")
/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名称的唯一方法是检查
os.name
Java属性(在WinXP上使用Jython 2.5.3的
sys
os
平台
模块进行了尝试):


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

这里有几个不同的可能的电话,你可以确定你在哪里

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、安腾、power pc、sparc)上运行,可在以下位置获得:

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

windows 8上有趣的结果:

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

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

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

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

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
试试这个:

import os

os.uname()
你可以做到:

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

如果您在使用Cygwin的Windows上,并且
os.name
posix
,请注意

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

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

>>> 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]

一个新的答案如何:

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

这将是我使用MACOS时的输出,如果您运行MACOS X并运行
platform.system()

因为MacOSX是建立在苹果的达尔文操作系统上的。Darwin是macOS X的内核,本质上是没有GUI的macOS X。

下面这样一个简单的枚举实现怎么样?不需要外部LIB

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
只需使用枚举值即可访问

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

p.S It is python3

此解决方案适用于
python
jython

模块os_identify.py:


您可以查看中的代码,该代码是pip date包的一部分,以获得最相关的操作系统信息,如您的Python发行版所示

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


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

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

Linux(64位)+WSL
  • 使用archlinux和mint进行了尝试,得到了相同的结果
  • 在python2
    sys.platform
    上,内核版本作为后缀,例如
    linux2
    ,其他所有内容保持不变
  • 除了
    platform.architecture()=('64bit','ELF')
WINDOWS(64位) (32位子系统中运行32位列)

一些评论:

  • 还有
    distutils.util.get_platform()
    ,它与'sysconfig.get_platform'相同
  • windows上的anaconda与官方python windows安装程序相同
  • 我既没有Mac电脑,也没有真正的32位系统,也没有在网上做这件事的动机
要与您的系统进行比较,只需运行此脚本(如果缺少,请在此处追加结果:)


我玩游戏迟到了,但为了防止有人需要,我使用此函数对代码进行调整,使其在Windows、Linux和MacOs上运行:

导入系统 def get_os(osoptions={'linux':'linux','Windows':'win','macos':'darwin'}): ''' 让操作系统允许代码细节 ''' opsys=[k表示osoptions.keys()中的k,如果sys.platform.lower().find(osoptions[k].lower())!=-1] 尝试: 返回操作系统[0] 除: 返回“未知操作系统”
短篇小说

使用
platform.system()
。它返回
Windows
Linux
Darwin
(对于OSX)

说来话长

有3种方法可以获得Python中的操作系统,每种方法都有自己的优缺点:

方法1

>>> import sys
>>> sys.platform
'win32'  # could be 'linux', 'linux2, 'darwin', 'freebsd8' etc
如何工作():它在内部调用OS API以获取OS定义的OS名称。有关各种特定于操作系统的值,请参阅

赞成者:不,m
if OS.LINUX.value:
    print("Cool it is Linux")
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()
os.name                     posix
sys.platform                linux
platform.system()           Linux
sysconfig.get_platform()    linux-x86_64
platform.machine()          x86_64
platform.architecture()     ('64bit', '')
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')

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())
>>> import sys
>>> sys.platform
'win32'  # could be 'linux', 'linux2, 'darwin', 'freebsd8' etc
>>> import os
>>> os.name
'nt'  # for Linux and Mac it prints 'posix'
>>> import platform
>>> platform.system()
'Windows' # for Linux it prints 'Linux', Mac it prints `'Darwin'
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
import platform
system = platform.system().lower()

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