Python 判斷 OS 作業系統的 3 種方法

本篇 ShengYu 介紹 Python 判斷 OS 作業系統的 3 種方法,以下的 Python 判斷 OS 作業系統的方法將分為這幾部分,

  • Python os.name
  • Python sys.platform
  • Python platform.system()

那我們開始吧!

Python os.name

Python 判斷 OS 作業系統的方法可以使用 os.name,這邊以 Python 3 為例,os.name 會回傳 posixntjava 這幾種結果,使用前要先 import os

1
2
3
4
5
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os

print(os.name)

Ubuntu 16.04 的輸出如下,

1
posix

MacOS 10.15.7 的輸出如下,

1
posix

Windows 10 的輸出如下,

1
nt

在 os 模組下還有另一個 uname() 函式可以使用,uname() 會回傳作業系統相關的版本資訊,

1
2
3
4
5
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os

print(os.uname())

Ubuntu 16.04 的輸出如下,

1
posix.uname_result(sysname='Linux', nodename='shengyu', release='4.10.0-40-generic', version='#44~16.04.1-Ubuntu SMP Thu Nov 9 15:37:44 UTC 2017', machine='x86_64')

MacOS 10.15.7 的輸出如下,

1
posix.uname_result(sysname='Darwin', nodename='shengyudeMacBook-Pro.local', release='19.6.0', version='Darwin Kernel Version 19.6.0: Thu Sep 16 20:58:47 PDT 2021; root:xnu-6153.141.40.1~1/RELEASE_X86_64', machine='x86_64')

Windows 下沒有 os.uname()

sys.platform 有更細的分類,下一節會介紹。

Python sys.platform

Python 判斷 OS 作業系統的方法可以使用 sys.platform,sys.platform 回傳的結果有 aixlinuxwin32cygwindarwin 這幾種,

1
2
3
4
5
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys

print(sys.platform)

Ubuntu 16.04 的輸出如下,

1
linux

MacOS 10.15.7 的輸出如下,

1
darwin

Windows 10 的輸出如下,

1
win32

sys.platform 回傳的種類情況分為這幾種,

系統種類 回傳值
AIX 'aix'
Linux 'linux'
Windows 'win32'
Windows/Cygwin 'cygwin'
macOS 'darwin'

Python 如果要用 sys.platform 判斷 OS 作業系統的話可以使用 startswith(),像 linux 與 linux2 的情況就可以被包含在以 linux 開頭的字串,寫在同一個條件式裡,

python3-detect-os.py
1
2
3
4
5
6
7
8
9
10
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys

if sys.platform.startswith('linux'): # 包含 linux 與 linux2 的情況
print('Linux')
elif sys.platform.startswith('darwin'):
print('macOS')
elif sys.platform.startswith('win32'):
print('Windows')

Python platform.system()

Python 判斷 OS 作業系統的方法可以使用 platform.system() 函式,platform.system() 會回傳作業系統的名稱,例如:LinuxDarwinJavaWindows 這幾種,如果無法判別作業系統的話會回傳空字串,

1
2
3
4
5
6
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import platform

print(platform.system())
print(platform.release())

Ubuntu 16.04 的輸出如下,

1
2
Linux
4.10.0-40-generic

MacOS 10.15.7 的輸出如下,

1
2
Darwin
19.6.0

Windows 10 的輸出如下,

1
2
Windows
10

以上就是 Python 判斷 OS 作業系統的介紹,
如果你覺得我的文章寫得不錯、對你有幫助的話記得 Facebook 按讚支持一下!

其它參考
When to use os.name, sys.platform, or platform.system?
https://stackoverflow.com/questions/4553129/when-to-use-os-name-sys-platform-or-platform-system
cross platform - Python: What OS am I running on? - Stack Overflow
https://stackoverflow.com/questions/1854/python-what-os-am-i-running-on

其它相關文章推薦
Python 新手入門教學懶人包