Last active
August 29, 2015 14:23
-
-
Save bnlucas/a23105c69132ab9e5fe9 to your computer and use it in GitHub Desktop.
Implement the Linux `which` command in Python that works in Windows!
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
def which(executable): | |
for path in os.environ['PATH'].split(os.pathsep): | |
path = path.strip('"') | |
fpath = os.path.join(path, executable) | |
if os.path.isfile(fpath) and os.access(fpath, os.X_OK): | |
return fpath | |
# checks if os is windows and appends .exe extension to | |
# `executable`, if not alread present, and rechecks. | |
if os.name == 'nt' and not executable.endswith('.exe'): | |
return which('{}.exe'.format(executable)) | |
return None | |
# tested on windows 8.1 | |
print which('python') # C:\Python27\python.exe |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment