Skip to content Skip to sidebar Skip to footer

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 interprete

Solution 1:

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 ; docommand -v > /dev/null $cmd && exec$cmd$0"$@"doneecho"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)

Solution 2:

If you can install scripts, you can also install a wrapper called python3.5 which simply dispatches python3.

#!/bin/shexecenv python3 "$@"

You'll obviously need to chmod a+x this script just like the others you install.

You'll have to add the script's directory to your PATHafter the system python3.5 directory to avoid having this go into an endless loop, and only use this script as a fallback when the system doesn't already provide python3.5.

As you noted, env doesn't know or care about your personal shell aliases or functions, and doesn't provide for any dynamic calculation of the binary to run by itself; but you have the shell at your disposal (and Python of course, once you find it!) -- it simply uses the PATH so if you can install your other scripts in a directory which is in your PATH (which must be the case for the #!/usr/bin/env shebang to make sense in the first place) you can store this script there, too.

As noted in comments, it's weird and user-hostile to only install python3.5 and not at least optionally make python3 a symlink to it, so perhaps you could eventually persuade whoever maintains the image you are installing into to provide this.

Solution 3:

You could create a shell script that uses python 3.5 if it is installed, otherwise uses python 3 and executes your script with the correct version. No need for python shebang. In your shell script you may test if which python3.5 returns something; if it does, then python3.5 is installed, otherwise you'd have to use python3

Post a Comment for "How To Make The Shebang Be Able To Choose The Correct Python Interpreter Between Python3 And Python3.5"