How to use 2to3 properly for python?

后端 未结 9 831
野趣味
野趣味 2020-12-04 17:26

I have some code in python 2.7 and I want to convert it all into python 3.3 code. I know 2to3 can be used but I am not sure exactly how to use it.

相关标签:
9条回答
  • 2020-12-04 17:59

    It's important to have a backup before running 2to3.

    1. If you're using git, make a commit.
    2. Otherwise, make a backup copy of your files.

    First, run 2to3 in "soft mode" to see what it would actually do:

    $ 2to3 /path/to/your/project
    

    If you're happy with what it would do, you can then run 2to3 "for real":

    $ 2to3 --write --nobackups /path/to/your/project
    

    And now you have properly run 2to3 :)

    0 讨论(0)
  • 2020-12-04 18:02

    Install the following module which adds the 2to3 command directly to entry_points.

    pip install 2to3
    

    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
    
    0 讨论(0)
  • 2020-12-04 18:03

    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.

    0 讨论(0)
  • 2020-12-04 18:07

    First install python 2to3 package :

    C:\Default> pip install 2to3
    

    Than convert your python2 file into python3 in your new folder i.e. python3-version/mycode

    C:\Default> 2to3 your_file_name.py --output-dir=python3-version/mycode -w -n
    

    Your new python3 file can be seen in new folder i.e. python3-version/mycode

    0 讨论(0)
  • 2020-12-04 18:15

    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.)

    0 讨论(0)
  • 2020-12-04 18:15

    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.

    0 讨论(0)
提交回复
热议问题