Skip to content

Commit f43417f

Browse files
committed
Added equivalent of shell utility "which" for Python
1 parent 0003635 commit f43417f

1 file changed

Lines changed: 35 additions & 0 deletions

File tree

src/bd2k/util/processes.py

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
import os
2+
3+
4+
def which( name, path=None ):
5+
"""
6+
Look for an executable file of the given name in the given list of directories,
7+
or the directories listed in the PATH variable of the current environment. Roughly the
8+
equivalent of the `which` program. Does not work on Windows.
9+
10+
:param executable_name: the name of the program
11+
12+
:type executable_name: str
13+
14+
:param path: an iterable of directory paths to consider or None if the PATH environment
15+
variable should be used
16+
17+
:returns: an iterator yielding the full path to every occurrance of an executable file of the
18+
given name in a directory on the given path or the PATH environment variable if no path was
19+
passed
20+
21+
>>> next( which('ls') )
22+
'/bin/ls'
23+
>>> list( which('asdalskhvxjvkjhsdasdnbmfiewwewe') )
24+
[]
25+
>>> list( which('ls', path=()) )
26+
[]
27+
"""
28+
if path is None:
29+
path = os.environ.get( 'PATH' )
30+
if path is None: return
31+
path = path.split( os.pathsep )
32+
for bin_dir in path:
33+
executable_path = os.path.join( bin_dir, name )
34+
if os.access( executable_path, os.X_OK ):
35+
yield executable_path

0 commit comments

Comments
 (0)