How to use 2to3 properly for python?

后端 未结 9 832
野趣味
野趣味 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!

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

    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

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

    To convert the code from python2 to python3 first install the 2to3 package by using

    pip install 2to3
    

    Then run this command in directory where is your python code

    2to3 -w -n .
    
    • -w flag to enable writeback, which applies the changes to the file
    • -n to disable backups
    0 讨论(0)
提交回复
热议问题