1.

Python script written using Python 2.x syntax is not compatible with Python 3.x interpreter. How can one automatically port Python 2.x code to Python 3.x?

Answer»

Python 3 was introduced in 2008. It was meant to be backward incompatible although some features have later been backported to Python 2.7. Still because of vast differences in specifications, Python 2.x code won’t run on Python 3.x environment. 

However, Python 3 library comes with a utility to convert Python 2.x code. This module is called 2to3. Command Line usage of this TOOL is as below:

$ 2to3 py2.py

To test this usage, save following code as py2.py

def sayhello(NM):     print "HELLO", nm nm=raw_input("enter name") sayhello(nm)

Above code uses Python 2.x syntax. The print statement doesn’t require parentheses. Also raw_input() function is not available in Python 3.x. Hence when we convert above code, print() function will have parentheses and raw_input will CHANGE to input()

As we run above command, a diff against the original source file is printed as below:

$ 2to3 py2.py RefactoringTool: Skipping optional fixer: buffer RefactoringTool: Skipping optional fixer: idioms RefactoringTool: Skipping optional fixer: set_literal RefactoringTool: Skipping optional fixer: ws_comma RefactoringTool: Refactored py2.py --- py2.py (original) +++ py2.py (refactored) -1,5 +1,5  def sayhello(nm): -    print "Hello", nm +    print("Hello", nm) -nm=raw_input("enter name") +nm=input("enter name")  sayhello(nm) RefactoringTool: Files that NEED to be modified: RefactoringTool: py2.py

2to3 can also write the needed modifications right back to the source file which is enabled with the -w flag. Changed version of script will be as shown.

$ 2to3 -w py2.py RefactoringTool: Skipping optional fixer: buffer RefactoringTool: Skipping optional fixer: idioms RefactoringTool: Skipping optional fixer: set_literal RefactoringTool: Skipping optional fixer: ws_comma RefactoringTool: Refactored py2.py --- py2.py (original) +++ py2.py (refactored) -1,5 +1,5  def sayhello(nm): -    print "Hello", nm +    print("Hello", nm) -nm=raw_input("enter name") +nm=input("enter name")  sayhello(nm) RefactoringTool: Files that were modified: RefactoringTool: py2.py

The py2.py will be modified to be compatible with python 3.x syntax

def sayhello(nm):     print("Hello", nm) nm=input("enter name") sayhello(nm)


Discussion

No Comment Found