How to use 2to3 properly for python?

后端 未结 9 939
野趣味
野趣味 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 18:16

    Running it is very simple! I am going to consider you already have it installed and explain step-by-step how to proceed after that:

    1. Open terminal (or cmd for win users) inside the main folder containing the files you want to convert

    e.g. C:\Users\{your_username}\Desktop\python2folder

    1. Type

    python {your_2to3.py_install_directory} -w .\

    e.g. in my case (win10) it would be:

    python C:"\Program Files"\Python39\Tools\scripts\2to3.py -w .\

    This is going to make the program scan the entire directory (and sub directories as well) and automatically convert everything that is written in Python2 to Python3.

    -w flag makes the script apply the changes creating new converted files. So remove this you'd like to just scan and see what needs conversion (but without actually doing anything)

    If you'd like to convert just one file instead of entire folders simply substitute .\ for python2_file_name.py:

    e.g. python {your_2to3.py directory} -w python2_file_name.py

    Also, by default it creates a .bak file for everything it converts. It is highly advised to keep it this way since any conversion is prone to errors but if you'd like to disable the automatic backup you could also add the -n flag.

    e.g. python C:"\Program Files"\Python39\Tools\scripts\2to3.py -w -n python2_file_name.py

    3.Done!

提交回复
热议问题