- $ 2to3 [-options] path/to/file.py
|filename / directory_name||2to3 accepts a list of files or directories which is to be transformed as its argument. The directories are recursively traversed for Python sources.|
|-f FIX, --fix=FIX||Specify transformations to be applied; default: all. List available transformations with |
|-j PROCESSES, --processes=PROCESSES||Run 2to3 concurrently|
|-x NOFIX, --nofix=NOFIX||Exclude a transformation|
|-l, --list-fixes||List available transformations|
|-p, --print-function||Change the grammar so that |
|-v, --verbose||More verbose output|
|--no-diffs||Do not output diffs of the refactoring|
|-w||Write back modified files|
|-n, --nobackups||Do not create backups of modified files|
|-o OUTPUT_DIR, --output-dir=OUTPUT_DIR||Place output files in this directory instead of overwriting input files. Requires the |
|-W, --write-unchanged-files||Write output files even is no changes were required. Useful with |
|--add-suffix=ADD_SUFFIX||Specify a string to be appended to all output filenames. Requires |
The 2to3 tool is an python program which is used to convert the code written in Python 2.x to Python 3.x code. The tool reads Python 2.x source code and applies a series of fixers to transform it into valid Python 3.x code.
The 2to3 tool is available in the standard library as lib2to3 which contains a rich set of fixers that will handle almost all code. Since lib2to3 is a generic library, it is possible to write your own fixers for 2to3.
Consider the following Python2.x code. Save the file as
In the above file, there are several incompatible lines. The
raw_input() method has been replaced with
input() in Python 3.x and
Running the above code will output the differences against the original source file as shown below.
The modifications can be written back to the source file using the -w flag. A backup of the original file called
example.py.bak is created, unless the -n flag is given.
example.py file has been converted from Python 2.x to Python 3.x code.
example.py will contain the following valid Python3.x code: