How to Get OS Information in Python

Updated: January 7, 2024 By: Guest Contributor Post a comment

Introduction

Accessing operating system (OS) details can be pivotal for various Python applications, from system monitoring to customizing UIs to align with the OS theme. In this tutorial, we will explore multiple methods and modules within Python to fetch OS-related data and how to interpret that data effectively.

Using the os Module

The os module in Python is a utility for interacting with the operating system. Here’s a basic example to get the current working directory:

import os

print(os.getcwd())

To get more detailed information about the OS, you can retrieve environment variables:

print(os.environ)

However, for a structured output specifically about the OS, you’d use os.name:

print(os.name)

Platform Module for Detailed OS Information

To get more detailed OS information, the platform module is your friend. For example, you can check the platform’s release, system name, or machine type:

import platform

print(platform.system())
print(platform.release())
print(platform.machine())

You can also fetch a comprehensive overview with platform.uname():

print(platform.uname())

Diving Deeper with Sys

The sys module offers utilities to interact with the Python interpreter and environment. Although not specifically for OS information, sys can provide several tidbits that are often relevant:

import sys

print(sys.platform)
print(sys.version)

Utilizing Psutil for Advanced System Insights

If you need more detailed and advanced system information, the third-party psutil module should suffice. It provides insight into system-wide resources utilization, including hardware and software details:

import psutil

print(psutil.cpu_times())
print(psutil.virtual_memory())

To install psutil, you need to run pip install psutil in your terminal.

Custom Function to Aggregate OS information

Combining the aforementioned modules, we can create a function to return a dictionary consisting of useful OS details:

import os
import platform
import sys


def collect_os_info():
    os_info = {
        'name': os.name,
        'system': platform.system(),
        'release': platform.release(),
        'machine': platform.machine(),
        'python_version': sys.version,
    }
    return os_info

print(collect_os_info())

Note that to collect even more data, we could wrap calls from the psutil module within our collect_os_info() function.

Conclusion

The ability to query OS details is a staple for Python developers looking to write adaptable and robust software. By harnessing the power of modules like os, platform, sys, and psutil, programmers can tailor applications to different environments with precision. As shown in this tutorial, the process is straightforward, and the information retrieved can be extremely useful for a variety of use cases.