Search code examples
xonsh

xonsh "which" equivalent - how to test if a (subprocess mode) command is available?


I would like to test (from xonsh) if a command is available or not. If I try this from the xonsh command prompt:

which bash

Then it works:

user@server ~ $ which bash                                                                                                           
/usr/bin/bash

But it does not work from xonsh script:

#!/usr/bin/env xonsh
$RAISE_SUBPROC_ERROR = True
try:
    which bash
    print("bash is available")
except:
    print("bash is not available")

Because it results in this error:

NameError: name 'which' is not defined

I understand that which is a shell builtin. E.g. it is not an executable file. But it is available at the xnosh command prompt. Then why it is not available inside an xonsh script? The ultimate question is this: how can I test (from an xonsh script) if a (subprocess mode) command is available or not?


Solution

  • import shutil
    print(shutil.which('bash'))