Home > python > make a script run under Python 2.x and 3.x too

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 :)

Update (20141228)
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.

Categories: python Tags: , , ,
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: