How to Find the Path of an Executable in Python?

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
print(shutil.which('python'))
# 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')
'C:\\Windows\\system32\\cmd.EXE'
>>> shutil.which('find')
'C:\\Windows\\system32\\find.EXE'
>>> shutil.which('help')
'C:\\Windows\\system32\\help.EXE'

Related Resources: