How to Check the Operating System with Python

In Brief...

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

  1. The function first creates a platforms dictionary of the most common operating system values returned by sys.platform.
  2. If the value returned by sys.platform is not found in the dictionary, the value itself is returned.
  3. Otherwise, a friendly name for the operating system retrieved from the platforms dictionary is returned.

Related Training

Author: Nat Dunn

Nat Dunn founded Webucator in 2003 to combine his passion for web development with his business expertise and to help companies benefit from both.