Reading Time: 1 minutes
Detecting platform in Python using sys.platform
The builtin sys module provides a very useful attribute called platform, which can be used to execute separate code blocks in different platforms. Following are the values of this attribute in different operating systems.
Platform | Value of sys.platform |
---|---|
FreeBSD | 'freebsd' |
Linux | 'linux' |
Windows | 'win32' |
Windows/Cygwin | 'cygwin' |
Mac OS X | 'darwin' |
>>> import sys >>> sys.platform 'win32' >>> if sys.platform.startswith('darwin'): print("I'm on a Mac OS X!") elif sys.platform.startswith('win32'): print("I'm on a Windows platform!") I'm on a Windows platform!
It is a safe bet to use the startswith() method to check platform values, since older versions of Python (less than 3.3) include the major version as well i.e. 'linux2', 'linux3'.