Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional shebang line for different versions of Python

I have a problem when trying to run a python script on two different computers. On each computer I would like to run the script using python version 2.7.3 however the problem I am having is that the two computers name python 2.7.3 in different ways. One of the computers runs arch linux and on this computer it is named python2. The other computer is running redhat linux and it uses the name python2.7.3.

What should I use in the shebang line so that the script is executable on both computers without requiring any changes? What I really want is some sort of conditional shebang line that could choose which version of Python to use. Am I just out of luck and I have to keep two different versions of the script?

P.S. I can't just use #!/usr/bin/env python as on the arch linux computer this would refer to python 3.2.3 and on the redhat linux computer it would refer to python 2.4.

like image 948
martega Avatar asked Aug 22 '12 09:08

martega


People also ask

Can a script have more than one shebang?

We can't have multiple shebang lines - there can only be one and it should always be the first line. If you need to support multiple versions of Python based on OS, it is best to write a small shell wrapper that invokes your python script with the right interpreter, probably with an exec .

Which one is the proper shebang for Python v3?

I have a third party script that uses the shebang #!/usr/bin/env python . According to the python documentation, this is the correct form for scripts that are suitable for both Python v2 and Python v3 (https://docs.python.org/3/using/windows.html#shebang-lines).

What is a valid shebang line in Python?

#!/usr/bin/env python """ The first line in this file is the "shebang" line. When you execute a file from the shell, the shell tries to run the file using the command specified on the shebang line. The ! is called the "bang". The # is not called the "she", so sometimes the "shebang" line is also called the "hashbang".


1 Answers

#!/bin/sh
# -*- mode: Python -*-

""":"
# bash code here; finds a suitable python interpreter and execs this file.
# prefer unqualified "python" if suitable:
python -c 'import sys; sys.exit(not (0x020500b0 < sys.hexversion < 0x03000000))' 2>/dev/null \
    && exec python "$0" "$@"
for pyver in 2.6 2.7 2.5; do
    which python$pyver > /dev/null 2>&1 && exec python$pyver "$0" "$@"
done
echo "No appropriate python interpreter found." >&2
exit 1
":"""

import sys
print sys.version

taken from https://github.com/apache/cassandra/blob/trunk/bin/cqlsh

like image 110
dhamu Avatar answered Oct 20 '22 00:10

dhamu