How to Check the Operating System with Python
Python is cross-platform and generally runs the same all operating systems, but if you're writing code that is operating-system dependent, you may need to check the OS. Here's a function for doing that.
Python Function for Checking the Operating System
import sys
def get_platform():
platforms = {
'linux1' : 'Linux',
'linux2' : 'Linux',
'darwin' : 'OS X',
'win32' : 'Windows'
}
if sys.platform not in platforms:
return sys.platform
return platforms[sys.platform]
How it works
- The function first creates a
platforms
dictionary of the most common operating system values returned bysys.platform
. - If the value returned by
sys.platform
is not found in the dictionary, the value itself is returned. - Otherwise, a friendly name for the operating system retrieved from the
platforms
dictionary is returned.