@ian-partridge’s method is great, especially for Python 3.3+. But let me add something interesting here for those who like a bit more manual control. If you want to simulate the which functionality without relying on shutil, you can use os.environ and iterate through the system’s PATH. This gives you more insight into how it works under the hood. Here’s a snippet:
import os
def which(file):
path_dirs = os.environ["PATH"].split(os.pathsep)
for directory in path_dirs:
executable = os.path.join(directory, file)
if os.path.isfile(executable) and os.access(executable, os.X_OK):
return executable
return None
file = 'python'
file_path = which(file)
if file_path:
print(f"The executable for '{file}' is located at: {file_path}")
else:
print(f"'{file}' not found.")
This method works for any version of Python, so whether you’re troubleshooting or just exploring ‘which python’ is being used, it’s a versatile choice!