Python alternative for Unix 'which' command?

I like how @shashank_watak gave us the manual route—really useful for learning the internals! But let’s not forget the power of leveraging existing Unix tools when working on Unix-based systems. If you prefer to directly invoke the which command itself from Python, the subprocess module has you covered. Here’s how you can do it:

import subprocess

def which(file):
    try:
        result = subprocess.run(['which', file], capture_output=True, text=True, check=True)
        return result.stdout.strip()
    except subprocess.CalledProcessError:
        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 approach essentially combines the best of both worlds—using the Pythonic way to call the native which command. If you ever find yourself asking ‘which python’ executable your system is picking up, this method is efficient and directly aligns with Unix practices.