Skip to content

Instantly share code, notes, and snippets.

@jquast
Created September 26, 2014 23:11
Show Gist options
  • Save jquast/a4e009d28428075ae073 to your computer and use it in GitHub Desktop.
Save jquast/a4e009d28428075ae073 to your computer and use it in GitHub Desktop.
def which(prog, error_msg=None):
"""
Execute and return output of 'which' command for argument `prog'.
@param error_msg: exception string for OSError
@type error_msg: string or None
@raises OSError: program 'prog' or 'which' system command not found
"""
try:
result = subprocess.Popen(('which', prog), stdout=subprocess.PIPE
).stdout.read().strip()
except OSError as err:
if err.errno != errno.ENOENT:
raise
raise OSError("`which' not found in environment PATH: {0}"
.format(os.environ.get('PATH')))
if not result:
raise OSError(error_msg or "`{0}' not found in environment PATH: {0}"
.format(prog, os.environ.get('PATH')))
return result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment