Python 3 – os.major() Method
In Python 3, the os module provides many functions for interacting with the operating system. One of these functions is the os.major() method. It returns the “major” component of the numeric release data returned by os.uname() on some platforms.
The os.major() method is used to extract the major version number from the output of os.uname() method. This method returns a tuple containing the following elements:
- sysname: The operating system name
- nodename: The name of the node, i.e. the hostname.
- release: The operating system release.
- version: The operating system version.
- machine: The machine type (CPU) i.e. x86_64, i686 etc.
The tuple returned by os.uname() method on macOS, Linux and most other Unix-like operating systems consists of all five of these strings. However, on Windows, the os.uname() function only returns the sysname and machine strings.
Here is an example of how we can use the os.major()
method to extract the major version number from the output of os.uname()
method:
import os
os_info = os.uname()
if os_info[0] == 'Windows':
print('Windows platform detected. major() method not supported.')
else:
major_version = os.major(os_info[2])
print(f"Operating system's major version is: {major_version}")
In the code above, we first import the os
module. We then use the os.uname()
method to get a tuple containing the details about the current operating system. Next, we check if the current operating system is Windows or not. If it is, then we print a message that os.major()
method is not supported on this platform. Otherwise, we extract the major version number using the os.major()
method and print it.
In the above code, os_info[2]
refers to the ‘release’ element of the tuple returned by the os.uname()
method. The major() method takes this string as input and returns the major version number. The major() method is only available on Unix and macOS systems.
Here’s another example which demonstrates how to use the os.major()
method with a platform that supports it:
import os
os_info = os.uname()
if os_info[0] == 'Linux':
major_version = os.major(os_info[2])
print(f"Operating system's major version is: {major_version}")
else:
print('Operating system not supported.')
In the code above, we again first import the os
module and use the os.uname()
method to get details about the current operating system. We then check if the current platform is Linux, and if so, we extract the major version number using the os.major()
method and print it. If the platform is not Linux, then we print a message that the operating system is not supported.
In conclusion, the os.major()
method is a useful tool for extracting the major version number of an operating system. It only works on Unix-like systems and macOS, so Windows users will not be able to use it. However, for those using compatible platforms, the os.major()
method can provide valuable information about the system they are running.