在很多情況下,需要在python中獲取當前系統的類型,用於判斷是unix/windows/mac或者java虛擬機等,python中提供了os.name, sys.platform, platform.system等方式,但是起初並不知道各個函數之間的區別以及在什麼情況下用那種。
函數簡介
首先,分別對每個函數進行說明,明確其提供的能力,以及如何使用。
os.name
官方文檔(v3.6.6)解釋如下:
os.name
The name of the operating system dependent module imported. The following names have currently been registered:
'posix'
,'nt'
,'java'
該變量返回當前操作系統的類型,當前只註冊了3個值:分別是posix
, nt
, java
使用方法:
import os
print(os.name)
sys.platform
sys.platform
This string contains a platform identifier that can be used to append platform-specific components to
sys.path
, for instance.
該變量返回當前系統的平臺標識。
對除了linux的Unix系統, 是uname -s
的返回值和uname -r
版本合併的小寫形式,例如linux2指的是使用2.x.x版本的linux系統。由於包含了系統版本,故推薦的使用方法是藉助startwith
函數。
import sys
if sys.platform.startwith('linux')
# linux 代碼
pass
elif sys.platform.startwith('freebsd')
# freebsd 代碼
pass
對windows系統, 返回值參考下表:
系統 | 返回值 |
---|---|
window | ’win32‘ |
linux | ’linux‘ |
Windows/Cygwin | ‘cygwin’ |
Mac OS X | ‘darwin’ |
這些值在編譯時已經確定了。
platform.system()
platform.system()
Returns the system/OS name, e.g.
'Linux'
,'Windows'
, or'Java'
. An empty string is returned if the value cannot be determined.
返回當前操作系統的名字,例如Linux
, Windows
, Java
, …如果不能確定會返回空字符串
這是在上層的腳本實現,需要在運行時執行。
主要區別
sys.platform
在構建配置時指定的編譯器定義os.name
用於檢查特定的某些模塊是否可用(例如:POSIX,nt, …)platform.system()
實際上運行uname和潛在的幾個其他函數來確定運行時的系統類型更多更及時的博客更新請戳—> KingRumn