Home > Software engineering >  Run a UNIX script to use different versions of python
Run a UNIX script to use different versions of python

Time:05-14

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.

CodePudding user response:

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]

CodePudding user response:

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.

  • Related