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.
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:
e.g.
C:\Users\{your_username}\Desktop\python2folder
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!
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 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 .