Python Programming: 判斷作業系統別

要識別作業系統是 Windows、Linux 還是 Mac,可能的方式有:

  • os.name – 傳回 ntposixdarwin (Mac OS X)、java (Jython) 等字串。
  • sys.platform – 帶有版號,例如 win32linux2darwinjava1.6.0_20 等,判斷時要用 startswith()
  • platform.system() – 傳回 WindowsLinuxDarwinJava 等字串。

比較下來,最直覺的方式就是透過 platform.system()

C:\>python
Python 2.7.2 (default, Jun 12 2011, 14:24:46) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import platform
>>> platform.uname()
('Windows', 'my-host-name', '7', '6.1.7600', 'AMD64', 'Intel64 Family 6 Model 23 Stepping 10, GenuineIntel')
>>> platform.system()
'Windows'
>>>

$ python
Python 2.6.6 (r266:84292, Sep 15 2010, 16:22:56)
[GCC 4.4.5] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import platform
>>> platform.uname()
('Linux', 'my-host-name', '2.6.35-32-generic', '#67-Ubuntu SMP Mon Mar 5 19:39:49 UTC 2012', 'x86_64', '')
>>> platform.system()
'Linux'
>>>

$ python
Python 2.7.3 (v2.7.3:70274d53c1dd, Apr  9 2012, 20:52:43)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import platform
>>> platform.uname()
('Darwin', 'WFBSSs-Mac-mini.local', '11.3.0', 'Darwin Kernel Version 11.3.0: Thu Jan 12 18:47:41 PST 2012; root:xnu-1699.24.23~1/RELEASE_X86_64', 'x86_64', 'i386')
>>> platform.system()
'Darwin'
>>>

例如:

import platform

if platform.system() == 'Windows':
    import _winreg

參考資料

廣告