]> git.phdru.name Git - ppu.git/blob - ppu/find_executable.py
Version 0.4.0: Add script which.py
[ppu.git] / ppu / find_executable.py
1 #!/usr/bin/env python
2
3
4 # https://gist.github.com/4368898
5 # Public domain code by anatoly techtonik <techtonik@gmail.com>
6 # AKA Linux `which` and Windows `where`
7
8
9 import os
10 import sys
11
12
13 def find_executable(executable, path=None):
14     """Find if 'executable' can be run. Looks for it in 'path'
15     (string that lists directories separated by 'os.pathsep';
16     defaults to os.environ['PATH']). Checks for all executable
17     extensions. Returns full path or None if no command is found.
18     """
19     if path is None:
20         path = os.environ['PATH']
21     paths = path.split(os.pathsep)
22     extlist = ['']
23     if os.name == 'os2':
24         (base, ext) = os.path.splitext(executable)
25         # executable files on OS/2 can have an arbitrary extension, but
26         # .exe is automatically appended if no dot is present in the name
27         if not ext:
28             executable = executable + ".exe"
29     elif sys.platform == 'win32':
30         pathext = os.environ['PATHEXT'].lower().split(os.pathsep)
31         (base, ext) = os.path.splitext(executable)
32         if ext.lower() not in pathext:
33             extlist = pathext
34     for ext in extlist:
35         execname = executable + ext
36         if os.path.isfile(execname):
37             return execname
38         else:
39             for p in paths:
40                 f = os.path.join(p, execname)
41                 if os.path.isfile(f):
42                     return f
43     else:
44         return None
45
46
47 if __name__ == '__main__':
48     print(find_executable('git'))