Search code examples
pythonportingpython-2to3

Make Python 2 compatible with Python 3


My current requirement is to write a script in Python 2.4.3 which comes bundled wit RHEL 5 . But few years down the line say 5 yrs ,the server may be upgraded to RHEL 8 or 9 which comes with Python 3. So I am supposed to write the code which is compatible with both version. Now my scripts contain basic operations such as creating directories, unzipping files, file manipulations, XML file reading ( which I am doing now with minidom ) and some hashing.

Now I found out that a tool called python-modernize does the work which is built on top of 2to3. I searched for the tool but I got a tar.gz file . It does not contain a python-modernize file as they say it in its usage. But all I found was a setup.py file. I am new to Python and all I know is that something is done with pip. But I also read that using pip is a tough work for Python 2.4.3 .

Please tell me how I can get the job done.

I also referred this but couldn't find how to use the tool.

Also please let me know if there are any good alternative to this.


Solution

  • Use the six libary from Benjamin Peterson.

    It was specifically designed for this very use-case. It allows you to have a single codebase that supports both Python 2 and Python 3 by importing the things that are different from 2 to 3 from the six library.

    Just simply import it and use it's definitions:

    import six
    

    Example:

    from six import u, b
    

    The above are classic where Python 3+ introduced stricter changes to the way Unicode Strings and Bytes work.

    Six is a Python 2 and 3 compatibility library. It provides utility functions for smoothing over the differences between the Python versions with the goal of writing Python code that is compatible on both Python versions. See the documentation for more information on what is provided.

    Six supports every Python version since 2.5. It is contained in only one Python file, so it can be easily copied into your project. (The copyright and license notice must be retained.)

    Update: Sorry I missed the Python<=2.5 requirement there; but honestly I think using six is your best option. YOu'll have to convince the powers that be that you have to use a minimum of Python 2.5.

    Update #2: My strongest recommendation is to upgrade your code to Python 2.7 as a minimum already. Don't get left behind or you'll always be behind the ball!

    Update #3: As per the above very helpful comments; I agree. Just work with what you've got right now. 5 years is indeed a long time and those same restrictions may not be in place by then!