platform


Platform Module

The platform module in Python provides information about the underlying platform on which your Python program is running. This information can be useful for customizing your program based on the platform or for debugging purposes.

Cross-Platform Functions

The following functions are available in the platform module for all platforms:

  • platform.system(): Returns the name of the operating system (e.g., 'Windows', 'Linux', 'Darwin').

  • platform.machine(): Returns the hardware architecture (e.g., 'x86_64', 'armv7l').

  • platform.processor(): Returns the processor type (e.g., 'Intel Core i5', 'ARM Cortex-A7').

  • platform.uname(): Returns a named tuple with system information (see below for details).

Named Tuple Returned by platform.uname()

The named tuple returned by platform.uname() provides the following information:

  • system: Operating system name (e.g., 'Windows')

  • node: Network node name (e.g., 'DESKTOP-ABC123')

  • release: Operating system release (e.g., '10.0.19041')

  • version: Operating system version (e.g., '#2-Microsoft Winpre Professional')

  • machine: Hardware architecture (e.g., 'x86_64')

Example Code

Here's an example of using the platform module:

import platform

print("Operating System:", platform.system())
print("Hardware Architecture:", platform.machine())
print("Processor Type:", platform.processor())

uname = platform.uname()
print("System Information:")
print("  - Name:", uname.system)
print("  - Node Name:", uname.node)
print("  - Release:", uname.release)
print("  - Version:", uname.version)
print("  - Machine:", uname.machine)

Output

The output of the example code will vary depending on the platform you're running on. For example, on a Windows 10 machine with an Intel Core i5 processor, the output might look like this:

Operating System: Windows
Hardware Architecture: x86_64
Processor Type: Intel Core i5
System Information:
  - Name: Windows
  - Node Name: DESKTOP-ABC123
  - Release: 10.0.19041
  - Version: #2-Microsoft Winpre Professional
  - Machine: x86_64

Potential Applications

The platform module can be useful in a variety of real-world applications, including:

  • Customizing your program based on the platform it's running on

  • Debugging platform-specific issues

  • Identifying the hardware and software environment of your system

  • Gathering information for system administration tasks


architecture() function in platform module

The architecture() function in Python's platform module provides information about the architecture of the given executable (defaults to the Python interpreter binary).

Parameters:

  • executable: Path to the executable to query. Default: sys.executable (Python interpreter binary)

  • bits: Optional parameter to specify the desired bit architecture ("","32","64"). Default: ""

  • linkage: Optional parameter to specify the desired linkage format used for the executable ("","static","dynamic"). Default: ""

Return Value:

A tuple (bits, linkage) containing the following information:

  • bits: String representing the bit architecture of the executable (e.g., "32", "64").

  • linkage: String representing the linkage format used for the executable (e.g., "static", "dynamic").

How it works:

The architecture() function relies on the system's file command to determine the architecture information. It uses the command file -L <executable> to get the executable's type and linkage format. If the bits parameter is not specified, it tries to determine the pointer size using sizeof(pointer) or sizeof(long) (depending on the platform).

Code snippet:

import platform

# Get architecture information of the Python interpreter
bits, linkage = platform.architecture()
print("Bit architecture:", bits)
print("Linkage format:", linkage)

Output:

Bit architecture: 64
Linkage format: dynamic

Real-world applications:

  • Detecting the architecture of a binary: Useful for determining the compatibility of a binary with your system.

  • Analyzing the linkage format of a binary: Helps in understanding how the binary was compiled and linked.

  • Automating cross-compilation: For building binaries for different architectures.


Simplified Explanation of platform.machine() Function:

Imagine your computer as a house. The "machine type" is like the type of house you have, such as a bungalow, a two-story house, or an apartment.

The platform.machine() function tells you the "machine type" of your computer, or the type of processor (CPU) it has. CPUs can be different, like different house designs. For example, you might have a computer with an Intel Core i5 CPU, which would be like having a two-story house with a modern design.

Code Snippet:

import platform

machine_type = platform.machine()
print(machine_type)

Real-World Examples:

  • A software developer might use platform.machine() to make sure their software works on different types of computers. For example, if you know your software will run on computers with Intel Core i5 or AMD Ryzen 5 CPUs, you can make sure to test it on both types to avoid any compatibility issues.

  • A system administrator might use platform.machine() to track the hardware of their computers. For example, they could use it to create a list of all the computers in their network that have Intel Core i7 CPUs and need to be upgraded.

Potential Applications:

  • Software Compatibility: Ensuring software works on different computer architectures.

  • Hardware Tracking: Managing and monitoring computer hardware.

  • System Optimization: Adapting performance to specific hardware configurations.


Function: node()

Simplified Explanation:

node() finds the name of your computer on the network. This lets other computers know how to find you. It's like your computer's address on the internet.

Code Snippet:

computer_name = platform.node()
print(computer_name)

How it Works:

When you run the code, platform.node() tries to get your computer's network name. If it succeeds, it prints the name. If it doesn't, it prints an empty string ("").

Real-World Examples:

  • Networking your computers to share files and printers.

  • Joining your computer to a company's network to access resources.

  • Troubleshooting network issues by checking the network name.

Potential Applications:

  • File Sharing: Sharing files between computers on the same network.

  • Printer Access: Allowing multiple computers to use the same printer.

  • Network Security: Monitoring network activity for security threats.

  • Remote Access: Accessing your computer from another location over a network.

  • Cloud Computing: Using cloud services that require your computer's network name for authentication.


platform Module

The platform module provides information about the underlying platform on which Python is running.

platform(aliased=False, terse=False)

This function returns a string identifying the platform. Here's a breakdown of its parameters:

  • aliased: If True, it uses aliases for some platforms (e.g., SunOS becomes Solaris).

  • terse: If True, it returns only the minimum information.

Example:

import platform

print(platform.platform())

Output could be something like:

Linux-5.10.23-generic-x86_64-with-Ubuntu-18.04-esm

This indicates you're running Python on Ubuntu 18.04 with Linux kernel version 5.10.23.

Applications:

  • System administration: Identify the platform for debugging or troubleshooting purposes.

  • Cross-platform development: Adapt your code to different operating systems based on the platform information.

  • Version checking: Ensure that your code runs on specific platforms or versions.


Simplified Explanation:

The processor() function in platform provides information about the real processor (CPU) of your computer.

Detailed Explanation:

  • Function Name: processor()

  • Description: Returns the name of the processor as a string. For example, "Intel Core i7" or "ARM Cortex-A7".

  • Return Value: A string with the processor name, or an empty string if the information is not available.

  • Note: Many platforms (operating systems like Windows, Linux, etc.) do not provide detailed processor information. In those cases, the function will return the same value as machine(), which provides general information about the computer.

Complete Code Implementation:

import platform

processor_name = platform.processor()
print("Processor Name:", processor_name)

Output:

Processor Name: Intel Core i7-4770K CPU @ 3.50GHz

Real-World Applications:

  • System Monitoring: You can use the processor name to identify the type and capabilities of your CPU.

  • Software Compatibility: Some software (e.g., video editing programs) may require specific processor features. You can use the processor name to check if your system meets the software requirements.

  • Troubleshooting: If you experience performance issues or other problems with your computer, the processor name can help you narrow down the cause.


python_build() Function

The python_build() function returns a tuple containing two strings:

  • buildno: The build number of the Python interpreter.

  • builddate: The date when the Python interpreter was built.

Simplified Explanation

Think of it like this: when your mom buys you a new bike, it comes with a sticker that says "Serial Number:" and a number like "0123456789." This number helps identify your bike if it gets lost. Similarly, the build number helps identify which version of Python you're using.

The build date is like the "date of purchase" for your bike. It tells you when the Python interpreter was made.

Real-World Example

import platform

# Get the build number and date of the Python interpreter
buildno, builddate = platform.python_build()

# Print the results
print("Python Build Number:", buildno)
print("Python Build Date:", builddate)

Output:

Python Build Number: 1011
Python Build Date: Feb 21 2022

Potential Applications

  • Troubleshooting: If you're having problems with your Python code, you can check the build number and date to see if there's a known bug in that version.

  • Version management: You can use the build number to ensure that you're using the correct version of Python for your project.

  • Research: You can use the build date to learn when a particular version of Python was released.


Function: python_compiler()

Simplified Explanation:

This function tells you what compiler (like a wizard) was used to turn your written Python code into computer-understandable instructions.

Detailed Explanation:

When you write Python code, it's like writing instructions in a different language. A compiler is like a translator that takes your instructions and turns them into a language that your computer can understand.

python_compiler() returns the name of the compiler used to translate your Python code. It could be:

  • CPython (written in C)

  • Jython (written in Java)

  • PyPy (written in Python itself)

Code Example:

import platform

compiler = platform.python_compiler()
print(compiler)

Output:

CPython

Real-World Applications:

  • If you're experiencing issues with your Python installation, knowing the compiler used can help you troubleshoot.

  • It can also be useful if you're curious about the underlying implementation of Python.


python_branch() Function

Purpose:

Returns a string that identifies the branch of the Python source code management (SCM) system used to build the Python interpreter.

Simplified Explanation:

Imagine Python as a tree with different branches growing from it. Each branch represents a different version or stage of Python's development. The python_branch() function tells you which branch was used to create the Python interpreter you're currently using.

Code Snippet:

import platform

python_branch = platform.python_branch()
print(python_branch)

Output:

The output will display the name of the SCM branch used to build the Python interpreter. For example:

main

Real-World Applications:

  • Debugging: Knowing the branch can help you determine if a bug you're experiencing is related to a specific version of Python.

  • Compatibility: If you're using a third-party module that depends on a specific SCM branch, this function can help you verify that you have the correct version installed.

  • Tracking Development: If you're interested in contributing to Python's development, this function can help you identify the latest changes and branches being worked on.


python_implementation() function

This function returns a string that identifies the Python implementation that you're using. The possible return values are:

  • 'CPython': This is the most common implementation of Python, written in C. It's the default implementation on most systems.

  • 'IronPython': This is an implementation of Python that runs on the .NET Framework. It allows you to write Python code that can interact with .NET objects and libraries.

  • 'Jython': This is an implementation of Python that runs on the Java Virtual Machine. It allows you to write Python code that can interact with Java objects and libraries.

  • 'PyPy': This is a just-in-time compiler for Python. It compiles Python code into machine code at runtime, which can make your code run faster.

Real-world example

The following code prints out the Python implementation that you're using:

>>> import platform

>>> platform.python_implementation()
'CPython'

This code can be useful if you need to know which Python implementation you're using for compatibility or debugging purposes.

Applications in the real world:

  • Troubleshooting: If you're having problems with a Python program, knowing which implementation you're using can help you find the right documentation or support resources.

  • Compatibility: If you're writing code that needs to be compatible with multiple Python implementations, you can use the return value of python_implementation() to make sure that your code works on all of them.


python_revision() Function

Simplified Explanation:

This function gives you a code identifying the version of Python that is currently installed on your computer.

Example:

>>> import platform
>>> platform.python_revision()
'6f7c14de7'

Real-World Application:

  • Checking if your Python version meets the requirements for a specific software or library.

  • Debugging issues related to different Python versions used in different environments.


Python Version

Simplified Explanation:

Python version tells you the specific version of Python you're using. Just like how you have versions of apps on your phone, Python has versions. Knowing the version is important because different versions may have different features or fixes.

Python Code Example:

import platform

print(platform.python_version())  # Output: '3.10.2'

Real-World Application:

  • Checking for compatibility with other libraries or tools that require specific Python versions.

Note: Unlike the Python sys.version, the platform.python_version() function always includes the patch level (the final number in the version, e.g., 2 in '3.10.2'). This provides a more precise version number.


python_version_tuple() Function

Purpose:

The python_version_tuple() function in Python's platform module returns a tuple containing the major, minor, and patchlevel of the current Python interpreter.

Explanation:

When you run a Python script, the Python interpreter is the program that interprets the script and executes its instructions. The python_version_tuple() function provides information about the version of the Python interpreter you're using.

Return Value:

The function returns a tuple with three elements:

  • major: The major version number (e.g., 3 for Python 3)

  • minor: The minor version number (e.g., 8 for Python 3.8)

  • patchlevel: The patchlevel (e.g., 0 for Python 3.8.0)

Example:

import platform

version_tuple = platform.python_version_tuple()

print(version_tuple)

Output:

(3, 8, 0)

This means you're using Python version 3.8.0.

Real-World Applications:

The python_version_tuple() function can be used in various scenarios:

  • Checking Compatibility: You can ensure that your code is compatible with a specific Python version before running it.

  • Debugging: If your code is behaving unexpectedly, you can check the Python version to see if it's a known issue for that version.

  • Version-Specific Features: Some Python features may only be available in certain versions. You can use the version tuple to determine if a feature is supported.


Simplified Explanation:

The release() function in the platform module provides information about the operating system's release version.

Function Details:

  • Definition: release() -> str

  • Purpose: Returns the release version of the operating system.

  • Return Value: A string representing the release version, or an empty string if the information is unavailable.

Examples:

  • Getting the release version of Windows:

import platform

print(platform.release())  # Output: '10'
  • Checking if the operating system is Windows XP:

import platform

release = platform.release()
if release == '5.1':
    print("You are running Windows XP")
else:
    print("You are not running Windows XP")

Real-World Applications:

  • Identifying the specific version of the operating system for compatibility checks.

  • Creating software that adapts to different operating system releases.

  • Providing detailed system information for debugging or troubleshooting purposes.

Improved Code Snippet:

def get_os_release():
    """Returns the operating system's release version."""
    import platform

    release = platform.release()
    if release:
        return release
    else:
        return "Unknown"

This snippet creates a function that returns the operating system's release version. It handles the case where the release information is unavailable and returns "Unknown" instead.


Function: system()

Purpose: To get the name of the operating system (OS) your Python program is running on.

Simplified Explanation:

Imagine you have a computer with different kinds of software or operating systems like Windows, macOS, or Linux. Think of your computer as a big machine with lots of little parts working together.

The system() function helps you figure out which kind of "big machine" your program is running on. It checks the specific parts in your computer and tells you the name of the operating system it finds, like "Windows" or "Linux".

Code Snippet:

import platform

# Get the system name
system_name = platform.system()

# Print the system name
print(system_name)

Output:

Windows

Real-World Applications:

  • Cross-platform compatibility: If you want your program to run on different operating systems, you can use the system() function to check the OS and adjust your program's behavior accordingly.

  • System-specific tasks: Some tasks or commands are different on different operating systems. For example, you might need to use different file paths or system calls based on the OS. The system() function helps you determine the OS so you can perform these tasks correctly.


Function: system_alias(system, release)

Purpose:

To handle specific formatting and reordering of system and release information for certain operating systems.

Simplified Explanation:

Imagine you're asked for information about your computer, like the operating system and the version it's running. Most computers will provide this information in a standard format, but some systems (like Windows) use a slightly different format.

The system_alias function takes in the system and release information and makes sure it's always in the same standardized format, so that it's easy to compare and understand for all systems.

Code Snippet:

import platform

# Get the current system and release information
system, release = platform.system(), platform.release()

# Use the `system_alias` function to format the information
formatted_system, formatted_release = platform.system_alias(system, release)

# Print the formatted information
print(f"System: {formatted_system}")
print(f"Release: {formatted_release}")

Real-World Example:

Suppose you're writing a program that depends on the underlying operating system. You want your program to work correctly on all platforms, so you need to be able to identify the system and release information. The system_alias function ensures that you always get the information in a consistent format, regardless of the operating system you're running on.

Potential Applications:

  • Identifying the operating system and version for software compatibility checks

  • Displaying the system and release information in a user-friendly manner

  • Configuring software based on the specific operating system environment


platform.release()

The platform.release() function returns the system's release, or version, as a string. e.g. 5.10.163-Microsoft

Potential Applications in Real World

  • you can check if the system is up to date or not by comparing it with the latest version available for your operating system

  • you can create a tool that can check the different versions of the systems of the different computers in a network

  • you can create a script that can automatically download and install the latest version of the operating system on all the computers in a network


uname() Function in Python's platform Module

The uname() function in Python's platform module provides a portable interface to retrieve system information. It returns a named tuple containing the following attributes:

Attribute
Description

system

Name of the operating system

node

Name of the host computer

release

Release version of the operating system

version

Detailed version information of the operating system

machine

Hardware architecture of the computer

processor

Type of CPU (resolved late, on demand)

Simplified Explanation

Imagine you have a computer with an operating system like Windows or Linux. The uname() function lets you find out details about your computer and operating system, like its name, version, and the type of processor it has.

Code Snippet

import platform

# Get system information
system_info = platform.uname()

# Print the system information
print("System:", system_info.system)
print("Node:", system_info.node)
print("Release:", system_info.release)
print("Version:", system_info.version)
print("Machine:", system_info.machine)
print("Processor:", system_info.processor)

Real-World Example

Suppose you're developing an application that needs to know the type of operating system and processor the user's computer has. You can use the uname() function to gather this information and tailor the application accordingly.

Potential Applications

  • Identifying the operating system and processor for compatibility checks

  • Determining system resources and performance capabilities

  • Logging system information for debugging and analysis

  • Providing user-friendly error messages based on system configuration


Simplified Explanation:

java_ver() function:

This function tells you information about the Java Virtual Machine (JVM) and the operating system (OS) it's running on. It returns a tuple of 4 pieces of information:

  1. release: The version of Java installed.

  2. vendor: The vendor of the Java software (usually "Oracle").

  3. vminfo: A tuple with 3 pieces of information about the JVM:

    • vm_name: The name of the JVM (e.g. "OpenJDK").

    • vm_release: The version of the JVM.

    • vm_vendor: The vendor of the JVM.

  4. osinfo: A tuple with 3 pieces of information about the OS:

    • os_name: The name of the OS (e.g. "Windows", "Mac OS X", "Linux").

    • os_version: The version of the OS.

    • os_arch: The architecture of the OS (e.g. "32-bit", "64-bit").

Example:

>>> import platform
>>> platform.java_ver()
('18', 'Oracle Corporation', ('Java(TM) SE Runtime Environment', '18', 'Oracle Corporation'), ('Windows', '10.0.19044', '64bit'))

Real-World Applications:

This information can be useful for:

  • Checking if a specific version of Java is installed for compatibility with software.

  • Debugging issues with Java programs based on JVM or OS versions.

  • Creating cross-platform software by targeting specific Java and OS versions.


Get Version Information for Windows

The win32_ver function in Python's platform module provides information about the Windows operating system version running on your computer. It returns a tuple with the following elements:

  • version: The Windows version number, e.g., "10.0.19043.1165"

  • release: The release level, e.g., "release"

  • csd: The cumulative service pack level, e.g., "Service Pack 2"

  • ptype: The processor type, e.g., "Multiprocessor Free"

Example:

import platform

# Get the Windows version information
version_info = platform.win32_ver()

# Print the version number
print("Windows version:", version_info.version)

# Print the release level
print("Release level:", version_info.release)

# Print the cumulative service pack level
print("Cumulative service pack level:", version_info.csd)

# Print the processor type
print("Processor type:", version_info.ptype)

Real-World Applications:

  • System Administration: Check the version and updates of Windows systems on a network.

  • Software Development: Tailor applications or libraries based on the specific Windows version and features available.

  • Security: Determine if a particular Windows system meets security requirements based on its version and updates.

  • Home Use: Easily check the version and updates of Windows on your home computer.


win32_edition() Function

Explanation:

This function tells you which version of Windows your computer is running, like if it's "Enterprise" or "ServerStandard."

Returns:

A string with the Windows edition name, or "None" if it can't figure it out.

Example:

import platform

windows_edition = platform.win32_edition()
if windows_edition is not None:
    print("Your Windows edition is:", windows_edition)
else:
    print("Couldn't determine the Windows edition.")

Applications:

  • Checking if your computer meets the requirements for a software program.

  • Tailoring your software to specific Windows editions.


win32_is_iot() Function

What is it?

This function checks if the operating system (OS) you're running is a specific type of Windows called an "IoT edition."

How does it work?

Windows has different editions, and some of them are designed for Internet of Things (IoT) devices. IoT devices are typically small, connected devices that don't need the full features of a regular PC.

Simplified Explanation:

Imagine you have a phone. It runs a special version of Android that's optimized for phones. Windows IoT editions are like that, but for special devices like smart home devices or industrial equipment.

Code Example:

import platform

if platform.win32_is_iot():
    print("Your OS is an IoT edition.")
else:
    print("Your OS is not an IoT edition.")

Output:

Your OS is a Windows IoT edition.

Potential Applications:

  • IoT Device Development: Check if your device is compatible with Windows IoT editions.

  • Security Assurance: Verify that the OS on an IoT device is an official IoT edition for security reasons.


mac_ver() Function

Purpose: The mac_ver() function retrieves information about the macOS version running on the machine.

Synopsis:

import platform

mac_info = platform.mac_ver()

Return Value: A tuple of strings containing the following information:

  • version: The macOS version number, e.g. "12.3.1"

  • dev_stage: The development stage of the macOS version, e.g. "beta" or "final"

  • non_release_version: Any additional non-release version information, e.g. "RC1"

Example:

import platform

mac_info = platform.mac_ver()
print("macOS Version:", mac_info.version)
print("Development Stage:", mac_info.dev_stage)
print("Non-Release Version:", mac_info.non_release_version)

Output:

macOS Version: 12.3.1
Development Stage: final
Non-Release Version:

Real-World Applications:

  • Software compatibility checks: Determine if an application requires a specific macOS version or development stage to run.

  • System information display: Gather detailed version information for display in system diagnostic tools or user interfaces.

  • Development stage tracking: Identify the development stage of the macOS version being used for testing or debugging purposes.


Simplified Explanation:

The libc_ver() function in Python's platform module helps you find out which C library version is being used by the Python interpreter. This library handles basic system functions and is essential for running Python programs.

Detailed Explanation:

Parameters:

  • executable: The path to the Python executable (usually sys.executable).

  • lib: The name of the C library to check (usually 'libc').

Return Value:

It returns a tuple containing two strings:

  • lib: The name of the C library.

  • version: The version of the C library.

Working of the Function:

The function reads and analyzes the Python executable file in chunks to determine which C library is linked to it. This is only reliable for executables compiled using gcc.

Example:

# Get the C library version used by the Python interpreter
import platform

lib, version = platform.libc_ver()
print("C library:", lib)
print("Version:", version)

Output:

C library: libc
Version: 2.31

Potential Applications:

  • Debugging: Identify the version of the C library being used to troubleshoot compatibility issues.

  • Security: Ensure that the C library is up-to-date with security patches.

  • Research: Understand the underlying infrastructure used by Python.


freedesktop_os_release Function

Purpose:

Get information about your operating system from a standardized file called "os-release."

How it Works:

  • This file stores details like the OS name, version, and build for most Linux distributions (except Android).

  • The function loads and reads this file, then puts all the information into a Python dictionary.

  • You can access this information using the dictionary keys.

Example Output (Dictionary):

{'NAME': 'Ubuntu',
 'ID': 'ubuntu',
 'ID_LIKE': 'debian',
 'PRETTY_NAME': 'Ubuntu 22.04 LTS (Jammy Jellyfish)',
 'VERSION': '22.04',
 'VERSION_ID': '22.04'}

Example Code:

import platform

info = platform.freedesktop_os_release()
print(info["NAME"])  # Output: 'Ubuntu'

Real-World Applications:

  • Identifying the OS on a server to customize scripts or configurations.

  • Displaying OS details in a GUI application like a system information tool.

  • Checking compatibility with different software versions based on OS details.