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

  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.
Author: Nat Dunn

Nat Dunn is the founder of Webucator (, a company that has provided training for tens of thousands of students from thousands of organizations. Nat started the company in 2003 to combine his passion for technical training with his business expertise, and to help companies benefit from both. His previous experience was in sales, business and technical training, and management. Nat has an MBA from Harvard Business School and a BA in International Relations from Pomona College.

Follow Nat on Twitter at @natdunn and Webucator at @webucator.

About Webucator

Webucator provides instructor-led training to students throughout the US and Canada. We have trained over 90,000 students from over 16,000 organizations on technologies such as Microsoft ASP.NET, Microsoft Office, Azure, Windows, Java, Adobe, Python, SQL, JavaScript, Angular and much more. Check out our complete course catalog.