La commande which en Python
-
Utilisez la fonction
shutil.which()pour émuler la commandewhichen Python -
Créer une fonction pour émuler la commande
whichen Python
Sous Linux, nous avons la commande which. Cette commande peut identifier le chemin d’un exécutable donné.
Dans ce tutoriel, nous allons émuler cette commande en Python.
Utilisez la fonction shutil.which() pour émuler la commande which en Python
Nous pouvons émuler cette commande en Python en utilisant la fonction shutil.which(). Cette fonction est un ajout récent à Python 3.3. Le module shutil propose plusieurs fonctions pour traiter les opérations sur les fichiers et leurs collections.
La fonction shutil.which() renvoie le chemin d’un exécutable donné, qui s’exécuterait si cmd était appelé.
Par exemple,
import shutil
print(shutil.which("python"))
Production:
C:\Anaconda\python.EXE
Dans l’exemple ci-dessus, le shutil.which() renvoie le répertoire de l’exécutable Python.
Créer une fonction pour émuler la commande which en Python
Sous Python 3.3, il n’y a aucun moyen d’utiliser la fonction shutil.which(). Ainsi, ici, nous pouvons créer une fonction en utilisant les fonctions du module os pour rechercher l’exécutable donné et émuler la commande which.
Voir le code suivant.
import os
def which(pgm):
path = os.getenv("PATH")
for p in path.split(os.path.pathsep):
p = os.path.join(p, pgm)
if os.path.exists(p) and os.access(p, os.X_OK):
return p
print(which("python.exe"))
Production:
C:\Anaconda\python.exe