. Advertisement .
. Advertisement .
The command which in Python is utilized by different operating systems to locate executables. If an argument is an alias, the command which will expand it and look for it following the path of users.
Do you know how to simulate this command in Python? If not, do not worry; this tutorial will teach you how to do so in two different methods with examples. Let’s check it out and follow along.
Method 1: Utilize The Shutil.Which() Feature To Simulate The Command Which In Python
You can simulate the command which utilizing the method
shutil.which(), the most recently added function in Python 3.3. The module shutil provides a number of functions to handle actions on files and associated collections. To be more precise, it facilitates the automation of the copying and deletion of files and folders.
shutil.which() gives back the path to an executable, which could execute when cmd is called. Thus, you can utilize it to locate a file on your device that is listed in the PATH.
Below is an example for you to use as a reference.
import shutil print(shutil.which("python"))
In this case, the directory containing the Python executable files is returned by
Method 2: Make A Function To Simulate The Command Which In Python
shutil.which() method cannot be used in Python versions below 3.3. Therefore, in this case, you can build a function that uses the features of the module os to look for the specified executable and simulate the command which.
In case you are not familiar with the module os, it is included in the basic utility modules for Python. This module os offers many functions for communicating with the operating system. Plus, the modules such as os.path and os have a wide range of file system-related functions.
Here is a sample code to help you better understand.
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"))
The Bottom Line
So there you have the thorough guide on how to simulate the command which in Python. This command shows the location of the provided command or files, offering you direct results.
Hopefully, this guidance with several examples has successfully explained how to perform this task. You can test out both approaches and choose the one that best suits your needs. Keep practicing, and you will soon become an expert at both approaches.Suppose you want to learn more about other commands in Python; why not start with the HDFS DFS command? You can check out this post to gain more information about this useful command.