Skip to content

Instantly share code, notes, and snippets.

@bnlucas
Last active August 29, 2015 14:23
Show Gist options
  • Save bnlucas/a23105c69132ab9e5fe9 to your computer and use it in GitHub Desktop.
Save bnlucas/a23105c69132ab9e5fe9 to your computer and use it in GitHub Desktop.
Implement the Linux `which` command in Python that works in Windows!
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