LinuxCommandLibrary

2to3

TLDR

Show changes without applying

$ 2to3 [script.py]
copy
Convert file in place
$ 2to3 -w [script.py]
copy
Convert entire directory
$ 2to3 -w [directory/]
copy
Apply specific fixers only
$ 2to3 -f [print] -f [import] [script.py]
copy
List available fixers
$ 2to3 -l
copy
Convert with backup
$ 2to3 -w -n [script.py]
copy

SYNOPSIS

2to3 [options] file|directory

DESCRIPTION

2to3 is an automated Python 2 to Python 3 code translator. It parses Python 2 source code and applies "fixers" that transform incompatible syntax and library calls to their Python 3 equivalents.
Common transformations include:
- print statement to print() function
- unicode to str, str to bytes
- raw_input() to input()
- Iterator methods (.iteritems() to .items())
- except Exception, e to except Exception as e
- Library renames (urllib, ConfigParser, etc.)
2to3 handles most mechanical changes but may require manual review for semantic differences between Python 2 and 3.

PARAMETERS

-w, --write

Write changes to files
-n, --nobackups
Don't create .bak backup files
-f fixer, --fix fixer
Apply specific fixer
-x fixer, --nofix fixer
Exclude specific fixer
-l, --list-fixes
List available fixers
-p, --print-function
Assume print function is already imported
-j n, --processes n
Run in parallel with n processes
-o dir, --output-dir dir
Write converted files to directory
-v, --verbose
More verbose output

CAVEATS

2to3 makes syntactic changes but cannot handle all differences. Code behavior may still differ, especially around:
- String/bytes handling
- Integer division
- Dictionary ordering (pre-Python 3.7)
- Unicode text processing
Running -w without -n creates .bak files that may clutter version control.
Python 2 reached end-of-life in January 2020. For major projects, consider modern porting tools like python-modernize or futurize.

SEE ALSO

python(1), python3(1), pip(1)

Copied to clipboard