Archive

Posts Tagged ‘transition’

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

November 3, 2014 Leave a comment

Problem
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.

Solution
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: , , ,

requests-transition

January 7, 2013 Leave a comment

With the package requests-transition you can use requests 0.x and the shiny new requests 1.x too. Requests 1.x changed some things, so if you don’t want to update your code, requests-transition can be useful.

After installation, you can simply select which version of requests to use:

  • import requests0 as requests
    (0.x)
  • import requests1 as requests
    (1.x)
Categories: python Tags: , , ,
Design a site like this with WordPress.com
Get started