Search code examples
python-3.xgruntjsgrunt-exec

Specify a python version with fallback in grunt exec


I have a Gruntfile with grunt-exec specified as follows:

exec: {
      python_command: {
        cwd: "../../",
        command: 'python3.7 -c "MY_PYTHON_CODE"'

I want to use python3.7 if it exists on the system, but otherwise fall back to using python3. What's the easiest way to do this?


Solution

  • You could probe $PATH, if you're willing to write a loop.

    This mostly sounds like a bash question: How do I find if cmd1 or cmd2 is available?

    If you'd like to assign to a "cmd" variable, then which is your friend:

    $ which xxx || which yyy || which python3.7 || which python3
    /usr/bin/python3.7
    

    If you're willing to live with some stderr noise, then this works:

    $ python3.7 -c 'print(1)' || python3 -c 'print(1)'
    

    Or tidy up the noise, if you're confident you won't see other errors:

    $ python3.7 -c 'print(1)' 2> /dev/null || python3 -c 'print(1)'
    
    $ (python3.7 -c 'print(1)' 2>&1 || python3 -c 'print(1)') | grep -v 'command not found'