How to use 2to3 properly for python?

こ雲淡風輕ζ 提交于 2019-11-28 06:17:04

As it is written on 2to3 docs, to translate an entire project from one directory tree to another, use:

$ 2to3 --output-dir=python3-version/mycode -W -n python2-version/mycode

If you don't have 2to3 on your path, you can directly invoke lib2to3:

python -m lib2to3 directory\file.py

And as the docs (and other answers) mention, you can use some flags for more customization:

  • the -w flag to enable writeback, which applies the changes to the file
  • the -n to disable backups

(there are a few more flags; see the docs for more information.)

stzdr

On Windows:

python {path_to_python}\tools\scripts\2to3.py --output-dir={output_dir} -W -n {input_dir}

path_to_python = directory where Python is installed

output_dir = directory where to output the Python3 scripts

input_dir = directory from where to read the Python2 scripts

To convert all python 2 files in a directory to 3, you simply could run $ C:\Program Files\Python\Tools\Scripts\2to3.py -w -n. inside the directory that you want to translate. It would skip all the non .py files anyway, and convert the rest.
note: remove the -n flag, if you want the backup file too.

The python 2to3.py file is mostly found in the directory C:/Program Files/Python/Tools/scripts if you already have python installed. I have python 3.6 and 2to3 is in the directory C:/Program Files/Python36/Tools/scripts. To convert a certain python 2 code to python 3, go to your command promt, change the directory to C:/Program Files/Python36/Tools/scripts where the 2to3 file is found. Then add the following command: python 2to3.py -w (directory to your script).

eg. C:\Program Files\Python36\Tools\scripts> python 2to3.py -w C:Users\Iykes\desktop\test.py.

the '-w' here ensures a backup file for your file is created.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!