make a script run under Python 2.x and 3.x too
I installed Manjaro Linux on one of my laptops, just to try something new. I’ve been using it for a week and I like it so far :) On my older laptop it runs smoother than Ubuntu.
Anyway, Manjaro switched to Python 3.x, that’s the default, thus “python” points to Python 3. I use Ubuntu on my other machines where Python 2 is the default. I would like to modify my scripts (at least some of them) to run on both systems.
For instance, in Python 2.x you call “raw_input”, while this function was renamed to “input” in Python 3.x.
Well, since January 2014 I start all my new scripts with this line:
from __future__ import (absolute_import, division, print_function, unicode_literals)
It ensures a nice transition from Python 2 to Python 3.
To solve the “raw_input” problem, you can add these lines:
import sys if sys.version_info >= (3, 0): raw_input = input
You can continue using “raw_input”, but if it’s executed with Python 3.x, “raw_input” will point to the “input” function.
Of course, the ideal solution would be to switch to Python 3, but I’m not ready for that yet :)
At the moment I’m updating my jabbapylib library. The new version will be released soon :) Since it’s a library, it should work with both Python 2 and Python 3. When I write a new script, I tend to use Python 3 these days, but a library is different. A library should support both Python 2.x and 3.x. The most widely used solution is the Six compatibility library, which is a joy to use. To solve the
raw_input issue for instance, just import the line
from six.moves import input
Then — just like in Python 3 — call the function “input()” to read from the standard input. For more info. read the official docs.