Ce tutoriel détaille l'utilisation de la fonction platform.architecture(), qui permet de déterminer l'architecture du système et de l'interpréteur Python. Cette information est cruciale pour garantir la compatibilité des logiciels, gérer les dépendances et optimiser les performances.
1. A propos de platform.architecture()
La fonction platform.architecture() fait partie du module platform de la bibliothèque standard Python. Elle retourne un tuple contenant deux informations essentielles :
- L'architecture des bits de l'exécutable Python (ex: '64bit', '32bit')
- Le format de liaison de l'exécutable (ex: 'ELF', 'WindowsPE', 'MachO')
Cette fonction est particulièrement utile pour :
- Vérifier la compatibilité avec des bibliothèques natives
- Adapter le comportement du code selon l'architecture
- Diagnostiquer des problèmes d'exécution
- Choisir la bonne version d'un package binaire
2. Exemple d'usage basique
2.1 Appel simple et structure du résultat
L'appel de base de la fonction ne nécessite aucun paramètre. Elle retourne toujours un tuple de deux éléments.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
import platform # Appel simple de platform.architecture() resultat = platform.architecture() print(f"Type du résultat : {type(resultat)}") print(f"Valeur du résultat : {resultat}") # Accès aux éléments individuels bits, linkage = platform.architecture() print(f"\nArchitecture (bits) : {bits}") print(f"Format de linkage : {linkage}") # Output typique sur un système 64 bits Linux : # Type du résultat : <class 'tuple'> # Valeur du résultat : ('64bit', 'ELF') # # Architecture (bits) : 64bit # Format de linkage : ELF |
2.2 Comparaison avec sys.maxsize
Il existe d'autres méthodes pour déterminer l'architecture. Comparons platform.architecture() avec sys.maxsize.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
import platform import sys # Méthode 1 : platform.architecture() arch_tuple = platform.architecture() print(f"Méthode platform.architecture() : {arch_tuple}") # Méthode 2 : sys.maxsize print(f"\nValeur de sys.maxsize : {sys.maxsize}") if sys.maxsize > 2**32: print("Interprétation : Système 64 bits") else: print("Interprétation : Système 32 bits") # Méthode 3 : struct.calcsize import struct print(f"\nTaille du pointeur (struct.calcsize('P')) : {struct.calcsize('P') * 8} bits") # Output sur système 64 bits : # Méthode platform.architecture() : ('64bit', 'ELF') # # Valeur de sys.maxsize : 9223372036854775807 # Interprétation : Système 64 bits # # Taille du pointeur (struct.calcsize('P')) : 64 bits |
3. Cas d'utilisation pratiques
3.1 Validation de compatibilité d'architecture
Vous pouvez vérifier si l'environnement d'exécution correspond aux exigences de votre application.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
import platform def verifier_architecture(requise="64bit"): """Vérifie si l'architecture correspond à celle requise.""" architecture_actuelle, linkage = platform.architecture() print(f"Architecture actuelle : {architecture_actuelle}") print(f"Architecture requise : {requise}") if architecture_actuelle == requise: print("Architecture compatible") return True else: print(f"ATTENTION : Architecture incompatible") print(f"Certaines fonctionnalités peuvent ne pas fonctionner") return False # Test de validation verifier_architecture("64bit") # Output sur système 64 bits : # Architecture actuelle : 64bit # Architecture requise : 64bit # Architecture compatible |
3.2 Sélection dynamique de bibliothèques natives
Cette fonction est essentielle pour charger les bonnes bibliothèques natives selon l'architecture.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
import platform import ctypes import os def charger_bibliotheque_native(nom_base): """Charge la bibliothèque native appropriée selon l'architecture.""" bits, linkage = platform.architecture() systeme = platform.system() print(f"Système : {systeme}") print(f"Architecture : {bits}") # Construction du nom de fichier selon l'architecture if systeme == "Windows": if bits == "64bit": nom_fichier = f"{nom_base}_x64.dll" else: nom_fichier = f"{nom_base}_x86.dll" elif systeme == "Linux": if bits == "64bit": nom_fichier = f"lib{nom_base}_x64.so" else: nom_fichier = f"lib{nom_base}_x86.so" elif systeme == "Darwin": # macOS nom_fichier = f"lib{nom_base}.dylib" else: raise OSError(f"Système non supporté : {systeme}") print(f"Bibliothèque à charger : {nom_fichier}") # Simulation du chargement (commenté car dépend de fichiers réels) # return ctypes.CDLL(nom_fichier) return nom_fichier # Exemple d'utilisation nom_bibliotheque = charger_bibliotheque_native("mabiblio") print(f"\nNom de la bibliothèque sélectionnée : {nom_bibliotheque}") # Output sur Linux 64 bits : # Système : Linux # Architecture : 64bit # Bibliothèque à charger : libmabiblio_x64.so # # Nom de la bibliothèque sélectionnée : libmabiblio_x64.so |
3.3 Rapport complet d'environnement
Combinez platform.architecture() avec d'autres fonctions pour créer un rapport détaillé.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 |
import platform import sys def rapport_environnement(): """Génère un rapport complet de l'environnement d'exécution.""" # Récupération des informations bits, linkage = platform.architecture() systeme = platform.system() release = platform.release() machine = platform.machine() processeur = platform.processor() version_python = platform.python_version() # Construction du rapport rapport = [] rapport.append("=" * 60) rapport.append("RAPPORT D'ENVIRONNEMENT D'EXÉCUTION") rapport.append("=" * 60) rapport.append("\n--- INFORMATIONS SYSTÈME ---") rapport.append(f"Système d'exploitation : {systeme} {release}") rapport.append(f"Architecture machine : {machine}") rapport.append(f"Processeur : {processeur}") rapport.append("\n--- INFORMATIONS PYTHON ---") rapport.append(f"Version Python : {version_python}") rapport.append(f"Architecture Python : {bits}") rapport.append(f"Format de linkage : {linkage}") rapport.append(f"Exécutable Python : {sys.executable}") rapport.append(f"Taille max des entiers : {sys.maxsize} (64 bits = {sys.maxsize > 2**32})") rapport.append("\n--- PLATEFORME DÉTECTÉE ---") rapport.append(f"Plateforme : {platform.platform()}") return "\n".join(rapport) # Affichage du rapport print(rapport_environnement()) # Output exemple sur Linux 64 bits : # ============================================================ # RAPPORT D'ENVIRONNEMENT D'EXÉCUTION # ============================================================ # # --- INFORMATIONS SYSTÈME --- # Système d'exploitation : Linux 5.15.0-91-generic # Architecture machine : x86_64 # Processeur : x86_64 # # --- INFORMATIONS PYTHON --- # Version Python : 3.11.4 # Architecture Python : 64bit # Format de linkage : ELF # Exécutable Python : /usr/bin/python3 # Taille max des entiers : 9223372036854775807 (64 bits = True) # # --- PLATEFORME DÉTECTÉE --- # Plateforme : Linux-5.15.0-91-generic-x86_64-with-glibc2.35 |
4. Détails techniques et pièges à éviter
4.1 Comportement sur différentes plateformes
Le comportement de platform.architecture() peut varier selon le système d'exploitation.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
import platform def tester_plateformes_simulees(): """Montre les différentes sorties selon les plateformes.""" print("Valeurs typiques de platform.architecture() :") print("-" * 50) print("\nSur Windows :") print("Windows 64 bits : ('64bit', 'WindowsPE')") print("Windows 32 bits : ('32bit', 'WindowsPE')") print("\nSur Linux :") print("Linux 64 bits : ('64bit', 'ELF')") print("Linux 32 bits : ('32bit', 'ELF')") print("\nSur macOS :") print("macOS 64 bits (Intel) : ('64bit', '')") print("macOS (Apple Silicon) : ('64bit', '')") print("\nAutres systèmes :") print("FreeBSD 64 bits : ('64bit', 'ELF')") print("\n" + "=" * 50) print(f"Votre système actuel : {platform.architecture()}") # Exécution du test tester_plateformes_simulees() # Output sur Linux 64 bits : # Valeurs typiques de platform.architecture() : # -------------------------------------------------- # # Sur Windows : # Windows 64 bits : ('64bit', 'WindowsPE') # Windows 32 bits : ('32bit', 'WindowsPE') # # Sur Linux : # Linux 64 bits : ('64bit', 'ELF') # Linux 32 bits : ('32bit', 'ELF') # # Sur macOS : # macOS 64 bits (Intel) : ('64bit', '') # macOS (Apple Silicon) : ('64bit', '') # # Autres systèmes : # FreeBSD 64 bits : ('64bit', 'ELF') # # ================================================== # Votre système actuel : ('64bit', 'ELF') |
4.2 Différence entre architecture système et architecture Python
Il est important de distinguer l'architecture du système de celle de l'interpréteur Python.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
import platform import subprocess def comparer_architectures(): """Compare l'architecture du système et celle de Python.""" # Architecture de l'interpréteur Python courant arch_python, linkage_python = platform.architecture() print(f"1. Architecture de CET interpréteur Python :") print(f" Bits : {arch_python}") print(f" Linkage : {linkage_python}") # Architecture du système (approximation) print(f"\n2. Architecture du système (via uname) :") try: # Pour Unix/Linux/macOS resultat = subprocess.run(['uname', '-m'], capture_output=True, text=True) if resultat.returncode == 0: print(f" Machine : {resultat.stdout.strip()}") except: pass # Pour une vérification plus précise print(f"\n3. Autres indicateurs :") print(f" platform.machine() : {platform.machine()}") print(f" platform.processor() : {platform.processor()}") # Vérification de cohérence print(f"\n4. Vérification :") machine = platform.machine() if '64' in machine and arch_python == '64bit': print(" Architecture système et Python cohérentes (64 bits)") elif '64' in machine and arch_python == '32bit': print(" ATTENTION : Système 64 bits avec Python 32 bits") elif '86' in machine or 'i386' in machine or 'i686' in machine: if arch_python == '32bit': print(" Architecture système et Python cohérentes (32 bits)") else: print(" Système 32 bits (ou compatible) avec Python 64 bits") # Exécution de la comparaison comparer_architectures() # Output sur Linux 64 bits avec Python 64 bits : # 1. Architecture de CET interpréteur Python : # Bits : 64bit # Linkage : ELF # # 2. Architecture du système (via uname) : # Machine : x86_64 # # 3. Autres indicateurs : # platform.machine() : x86_64 # platform.processor() : x86_64 # # 4. Vérification : # Architecture système et Python cohérentes (64 bits) |
Younes Derfoufi
CRMEF OUJDA



![[App intégrée] 2025 Upgraded Vidéoprojecteur 1920 * 1080P FHD 4K Mini Projecteur Portable Dual Contrôle avec Souris Android TV WiFi 6 BT5.2 180° Rotation Compatible avec HDMI/TV Stick/USB](https://www.tresfacile.net/wp-content/uploads/2025/12/Videoprojecteur-1920-1080P-FHD-4K-Mini-Projecteur-Portable-Dual-Control-250x236.png)