How to collect current architecture in Python 3, in a way that is portable across Linux, Windows and MacOS?

Viewed 685

I'm trying to find a portable way to collect the current architecture (e.g. x86_64 or AArch64) that I'll use to populate a flag like is_x86, using Python 3.

It looks like the import platform; platform.machine() function is the right one, but it gives me different strings, that in the end represent the same (broadly speaking) underlying architecture:

On Linux x86_64:

Python 3.6.9 (default, Nov  7 2019, 10:44:02) 
[GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import platform; platform.machine()
'x86_64'

Windows x86_64:

Python 3.6.8 (tags/v3.6.8:3c6b436a57, Dec 24 2018, 00:16:47) [MSC v.1916 64 bit (AMD64)] on win32
>>> import platform; platform.machine()
'AMD64'

MacOS x86_64:

Python 3.7.7 (default, Mar 10 2020, 15:43:33) 
[Clang 11.0.0 (clang-1100.0.33.17)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import platform; platform.machine()
'x86_64'

There is also i386 that is reported on x86 (32-bits) systems.

Is there any other way to reliably collect the architecture, in a portable way?

1 Answers

The simpler way I found to do it is:

import platform

is_x86 = platform.machine() in ("i386", "AMD64", "x86_64")

This is necessary due to the differences in strings returned under different operating systems.

Related