Get OS name and version in Python
Python programming has several modules that can be used to retrieve information about the current operating system and the version that is running on the system. In this article we will explore How to get the OS name and version in Python.
Let us see a simple example to get the OS name and version in Python.
import os
print (os.name)
import os
print (os.name)
Output
posix
Explanation: The os module has an attribute name that tells the current OS running on the system. Depending on the OS the code is executed on, it will give the OS name. For example, when this code is running on Windows, it will return "nt" and when it is running on Unix-based system, it returns "posix".
Let us see other ways to get the OS name and version in Python.
Using Platform Module
The platform module in Python is used to retrieve the information about the platform on which the program is running. This module has various functions that can be used to get the information like the OS name and its version.
Using name()
name() function returns a tuple, which contains system name, name of the machine on the network, release, OS version and machine name.
import platform
print(platform.uname())
import platform
print(platform.uname())
Output
uname_result(system='Linux', node='6c42885e148b', release='5.15.0-1072-aws', version='#78~20.04.1-Ubuntu SMP Wed Oct 9 15:30:47 UTC 2024', machine='x86_64', processor='')
Using system()
The system() function of the platform module gives the OS name and the version() function tells the current version of the OS installed on the machine.
import platform
print("OS Name:", platform.system())
print("OS Version:", platform.version())
import platform
print("OS Name:", platform.system())
print("OS Version:", platform.version())
Output
OS Name: Linux OS Version: #78~20.04.1-Ubuntu SMP Wed Oct 9 15:30:47 UTC 2024
Using sys Module
Python sys module can also be used to get the OS name and its version. The sys.platform gives a string value of the platform identifier. For Windows OS, it returns 'win32', for Linux, it returns 'linux', and for macOS, it returns 'darwin'.
import sys
print("OS platform:", sys.platform)
import sys
print("OS platform:", sys.platform)
Output
OS platform: linux