How to Find the Path of an Executable in Python?

Rate this post

Python’s shutil.which(cmd) function returns the path to the executable that would run if you called cmd in the command line. If there is no such executable, it returns None. The shutil module is part of the standard library, so you only need to add the statement “import shutil” to your program without needing to install it first.

Here’s a minimal example that searches for the path of the 'python.EXE' executable on my Windows machine:

import shutil
# C:\Users\xcent\AppData\Local\Microsoft\WindowsApps\python.EXE

Let’s confirm that the executable is indeed on this location by using the ls command in my PowerShell to list the directory content:

Figure: The executable 'python.EXE' at the retrieved file location.

Let’s test a couple of more executable locations:

>>> shutil.which('cmd')
>>> shutil.which('find')
>>> shutil.which('help')

Related Resources: