Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write a shebang line that will call either either python3 or python2 whichever is available

Recent releases of popular linux distributions have chosen to not install any python command by default. This makes it incredibly difficult to write portable scripts that works on both older and newer systems.

The smelly options:

  • rewriting the scripts at packaging or install time
  • forcing the user to call the script specifically with the versioned python interpreter
  • expecting the user will have run update-alternatives or similar

Is there a way to write a shebang #! line that uses only generally installed standard linux standard tools and can run either python3,python2, or python ?

I want something like a fictional --choices argument to the env command

#!/usr/bin/env --choices python3,python2,python

But of course that doesn't exist.

like image 562
Mark Borgerding Avatar asked Oct 29 '25 14:10

Mark Borgerding


1 Answers

Building on an idea at https://stackoverflow.com/a/9051635/13596037, you could do for example:

#!/bin/bash
'''':
for interpreter in python3 python2 python
do
    which $interpreter >/dev/null 2>&1 && exec $interpreter "$0" "$@"
done
echo "$0: No python could be found" >&2
exit 1
# '''


import sys
print(sys.version)
like image 127
alani Avatar answered Nov 01 '25 05:11

alani



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!