How To Porting Python3 Code To Python2 (3to2)

# 1. Use package ‘3to2’

The ‘3to2’ refer below:

  1. https://bitbucket.org/amentajo/lib3to2/src/default/
  2. https://pypi.org/project/3to2/

1.1. Install

Install ‘3to2’ package in your python 3 env.

Note! Attention! Please!

If you installed python2 and python3.

run:

pip3 install 3to2

pip default using version is python2. pip3 is using for python3.

So! pip3 install 3to2 will be recommended, while your system have to version of python 2 and 3.
Because 3to2 only run in python version > 3.x
Because of this reason, I met the some frustation. So, that’s all.

1.2. Usage

You can get the file 3to2 from https://bitbucket.org/amentajo/lib3to2/src/default/.

Or create a file 3to2 at the folder you want to porting you code from python3 to python2.

The code of 3to2 is below:

#!/usr/bin/env python3
import sys

from lib3to2.main import main

sys.exit(main("lib3to2.fixes"))

Then, run like this to cover the python3 code to python2:

python3 ./3to2 upload.python2.py -w

-w: means write the change to current file,and make a bak file at the same folder sametime.

# 2. Test ENV

  • System: Kali(debian 8)
  • python: 3.6 and 2.7