In this tutorial, you will learn how to determine the current operating system where the python script is running using various methods.
Python Detect OS - Platform Module
platform module in Python is part of the standard library. It contains information about the underlying system hardware. We can use the various methods from this module to determine the OS.
Example code is as demonstrated:
import platform os = platform.system() print("Current OS: ", os)
Current OS: Linux
In the code above, we start by importing the
platform module. We then call the
system() function from the module which gives us the OS name.
If you are running the script on Windows and MacOS, you will get an output as shown, respectively.
'Windows' [for Windows OS] 'Darwin' [for mac OS]
Python Detect OS - SYS Module
You are probably familiar with the
sys module in Python. This module provides ways of interacting with the running operating system including reading files, environment variables, user information, os information and more.
We can use this module to determine the current OS as shown in the code below:
import sys os = sys.platform() print("Current OS: ", os)
Current OS: linux
For other systems, respective output include:
'win32' -> [Windows: win32] 'darwin' -> [mac OS]
In this tutorial, you came across two simple yet useful methods of determining the current OS using Python. There is not much difference between the two methods, hence use the ones that comes naturally.