Last active
December 25, 2022 22:08
-
-
Save jamescherti/53e5d3bb4da597f24f4fe8c42fe49ea1 to your computer and use it in GitHub Desktop.
which() is a Python method that returns the full path of a (shell) command.
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
#!/usr/bin/env python | |
# Author: James Cherti | |
# License: MIT | |
# URL: https://gist.github.com/jamescherti/53e5d3bb4da597f24f4fe8c42fe49ea1 | |
"""Which() is a Python method that returns the full path of a (shell) command.""" | |
from pathlib import Path | |
import os | |
def which(command: str) -> Path: | |
"""Return the full path of a (shell) command.""" | |
if os.path.isfile(command) and os.access(command, os.X_OK): | |
return Path(command) | |
try: | |
path_dirs = [Path(item.strip()) | |
for item in os.environ["PATH"].split(os.pathsep)] | |
except KeyError: | |
path_dirs = [] | |
for path in path_dirs: | |
cmd_path = path.joinpath(command) | |
if os.access(str(cmd_path), os.X_OK): | |
return cmd_path | |
raise FileNotFoundError("the command '{}' wasn't found." | |
.format(command)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment