DEV Community

threadspeed
threadspeed

Posted on

OS detection in Python

Python can run on many platforms (Mac, Windows, Linux and others). Did you know it is super simple to detect the platform?

Python comes with the platform module that makes this easy. It is part of the Python standard library.

Start the Python shell and type this:

>>> import platform
>>> platform.architecture()
>>> platform.python_version()
>>> platform.uname()

An example run of the function calls:

>>> import platform
>>> platform.architecture()
('64bit', 'ELF')
>>> platform.python_version()
'3.7.7'
>>> platform.uname()
uname_result(system='Linux', node='localhost.localdomain', release='5.6.7-200.fc31.x86_64', version='#1 SMP Thu Apr 23 14:22:57 UTC 2020', machine='x86_64', processor='x86_64')
>>> 

The last call uname() returns a tuple. If you only want to know the operating system, you can do this:

import platform                                                                                                      

d = platform.uname()                                                                                                 
os = d[0]                                                                                                            
print(os)   

The uname function returns system, node, release, version, machine, and processor.

You can unpack the tuple like this:

import platform

d = platform.uname()
system, node, release, version, machine, cpu = d
print(system)
print(node)
print(release)
print(version)
print(machine)
print(cpu)

Related:

Top comments (0)