0

I have a UNIX script which is used to initialize the environment and properties of the project. It uses python. I had to refer the path. This will be used as a common file and used across multiple developers. Few of the machines uses Python 1.x and 2.x. Few others uses only Python 3.x.

So /usr/bin/python works for the machines run Python 1.x but it fails in machines running python 3.x. I have to explicitly change it to /usr/bin/python3 to make it work.

How can I handle the situation to make the script run independent of the python version installed.

Joseph
  • 1,060
  • 3
  • 22
  • 53
  • 2
    Python *1.x*!? A 22+ year old version?! – deceze May 13 '22 at 14:52
  • Usually when Python 3 is installed, the command `python` should be available and be an alias for `python3`. If the script supports both Python 2 and 3, then it shouldn't matter whether `python` refers to Python 2 or 3. In other words, it should work simply with `/usr/bin/python` either way, no? – deceze May 13 '22 at 14:56
  • I started in this line of work in 2008, and i've never seen python 1.x in the wild. – jordanm May 13 '22 at 14:56
  • Maybe helpful: https://askubuntu.com/a/321000/345778 – Klaus D. May 13 '22 at 15:28

2 Answers2

1

Python 1 or 2 are dead obviously, but I'll try to answer your question

In this this case you should have seprate binaries for each python version, similar to:

  • /usr/bin/python1
  • /usr/bin/python2
  • /usr/bin/python3

In your script define the version you want to use using shebang

For example make a file my_old_script.py:

#!/usr/bin/python2

import sys

print(sys.version)

Give the script execution permission:

chmod +x my_old_script.py

Then execute it without specifying an interpreter:

./my_old_script.py

output:

2.7.17 (default)
[GCC 7.5.0]
martineau
  • 119,623
  • 25
  • 170
  • 301
ahmed
  • 5,430
  • 1
  • 20
  • 36
  • 1
    That makes the script entirely dependent on which python version is installed, the question is how to make it independent. – ljmc May 13 '22 at 16:21
  • That's simply not possible without some weird hacking, this is one why to handle tasks with different scripts and python versions. This how current must distro handle python2 and 3 distribution, in Ubuntu you will find python3, python3.x and python2 each point to a different version of python – ahmed May 14 '22 at 00:09
0

Python2 is dead (less so that python1, but still dead), so it should be less and less of an issue. If you are worried about python2/3 compatibility, there is six and most things have been backported through the __future__ module, hopefully those two should be enough for your use cases.

ljmc
  • 4,830
  • 2
  • 7
  • 26