Search code examples
pythonbashpython-3.xshellshebang

How to make the Shebang be able to choose the correct Python interpreter between python3 and python3.5


I'm developing a set of script in python3, as shebang I use this:

#!/usr/bin/env python3

Everything goes ok, but in some virtual machines where are executed the name of interpreter is python3.5. I will like to be able to execute my scripts in both enviroment but I can't change the filesystem of virtual machine (so I discard solutions like make a link from python3.5 to python3 )

I look at man of env but I don't find any way to specify a searching pattern or something like that.

I try to set an alias at begining of my sessions pointing to right python interpreter but env don't use it.

My unique solution is call my scripts saying which interpreter must use but is very anoying:

python3.5 myscript.py

Any idea is welcome!, thanks!


Solution

  • No need to bring in separate shell and python scripts, a single file can be both!

    Replace your shebang line with this sequence:

    #!/bin/sh
    
    # Shell commands follow
    # Next line is bilingual: it starts a comment in Python, and is a no-op in shell
    """:"
    
    # Find a suitable python interpreter (adapt for your specific needs) 
    for cmd in python3.5 python3 /opt/myspecialpython/bin/python3.5.99 ; do
       command -v > /dev/null $cmd && exec $cmd $0 "$@"
    done
    
    echo "OMG Python not found, exiting!!!!!11!!eleven" >2
    
    exit 2
    
    ":"""
    # Previous line is bilingual: it ends a comment in Python, and is a no-op in shell
    # Shell commands end here
    # Python script follows (example commands shown)
    
    import sys
    print ("running Python!")
    print (sys.argv)