简体   繁体   中英

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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM