python 判断操作系统类型

[Python之道] 几种判断操作系统类型的方式

在实际项目中有时候不知道操作系统的类型,比如是Windows、OS X、*Unix?而Python代码虽说是跨平台(CrossPlatform)的,但是毕竟他们还是有些不同的,有的函数方法只能在某些操作系统下实现,这时考虑到程序的可移植性,需要在代码中对当前所在的操作系统做一个判断。

如果只想判断操作系统的类型,可调用 sys 库中的 platform 属性: sys.platform 。它能返回简单的属性:操作系统类型(Windows?Linux?还是其他)。例如,在Windwos 10 64位系统下Python2的解释器中运行,显示结果 win32 ;Python3的解释器中运行,显示结果也为 win32 。Windows 7 64位系统下显示结果同Win10。Debian 9(一个Linux的发行版)下Python2的显示结果为 linux2 ,Python3的显示结果为 linux 。这说明我们可以用 win32 这个返回值来判断当前系统是Windwos,返回 linux 则说明是Linux系统。(由于手上没有Windows 32位版本的系统,故没有测试在它们上门的运行结果,猜测也差不多;另外十分好奇Linux python2返回的结果中为什么会有一个2……)

还有一种方法是调用 os 库中的 name 属性: os.name 。它的返回值有两种: ntposix 。其中, nt 表示Windwos系操作系统, posix 代表类Unix或OS X系统。

那如果我们想要知道更详细的信息呢?想要更详细的区分?这时候就要用到 platform 库了。
platform.system 方法会返回当前操作系统的类型,Windows?Linux?OS X?Unix?FreeBSD?它能比较详细的区分。(其他的一般只能识别Windows和非Windwos)
platform.release 方法会返回当前操作系统的版本。笔者的测试环境是Windows 10 64位,它返回的结果是 10 。(Python2和Python3都一样)。相应的,如果是Windows 7,则会返回 7 ;Windows XP则返回 XP有点特殊的是对于Linux发行版,它返回的是内核(kernel)的版本号。 这点要注意。
platform.version 方法返回的则是当前系统的版本号,这个就不细说了。
platform.machine 方法返回的是系统的结构,64位or32位。
platform.uname 方法返回一个 元组 ,里面包含了当前操作系统的更详细的信息,方便调用。

------------------------------------------------------------------------------------------------------------------------------------------------------------

#!/bin/python
#
import platform

def TestPlatform():
    print ("----------Operation System--------------------------")
    #Windows will be : (32bit, WindowsPE)
    #Linux will be : (32bit, ELF)
    print(platform.architecture())

    #Windows will be : Windows-XP-5.1.2600-SP3 or Windows-post2008Server-6.1.7600
    #Linux will be : Linux-2.6.18-128.el5-i686-with-redhat-5.3-Final
    print(platform.platform())

    #Windows will be : Windows
    #Linux will be : Linux
    print(platform.system())

    print ("--------------Python Version-------------------------")
    #Windows and Linux will be : 3.1.1 or 3.1.3
    print(platform.python_version())

def UsePlatform():
  sysstr = platform.system()
  if(sysstr =="Windows"):
    print ("Call Windows tasks")
  elif(sysstr == "Linux"):
    print ("Call Linux tasks")
  else:
    print ("Other System tasks")

UsePlatform()

猜你喜欢

转载自blog.csdn.net/u012308586/article/details/108348291