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:
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'
While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.
To help students reach higher levels of Python success, he founded the programming education website Finxter.com. He’s author of the popular programming book Python One-Liners (NoStarch 2020), coauthor of the Coffee Break Python series of self-published books, computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.
His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.