Convert python 2 to 3 code in PyCharm

I have a big ML project in python 2 code, and I just started using PyCharm as an IDE. I am currently using WinPython 3.4, and I would prefer to do everything in python 3 instead of continuing to use deprecated 2. When I cloned a project from git, a pop-up window appeared in pycharm that was something like converting code to 3 from 2, but I did not think about it and left it. How to convert it?

+8
git python pycharm
source share
5 answers

I found a way in the Pycharm IDE to convert a file from v2 to v3 using the 2to3 tool.

I used the pycharm comunity v 2016.2.3 application on a windows environment.

  • Click terminal in status bar. You are now in the shell team, at the root of your project.
  • enter the command (to convert myfile.py):

    2to3 myfile.py -w

The tool modifies the file code, and your IDE is reflected with the changes.

To change all the files in a folder, enter the command

2to3 . -w 

The -w option to write changes. For more information write:

  2to3 -h 
+25
source share

Go to the folder where your python2script.py exists on the command line,

then run the command:

python C: /python/Tools/scripts/2to3.py -w python2script.py

you can see that your python2scipt.py has been updated.

+3
source share

Here the script is included in Python, usually in [Python Root]/Tools/Scripts/2to3.py . You can run this script in a python file (or in the python files directory) and handle many conversions, at least for changes to the standard library.

This gets a little trickier if your project uses other third-party libraries. Perhaps the API for those who changed during the 2-to-3 transition, and the 2to3.py script will not know about these api changes. It is best to do the conversion script, and then manually make any other changes you need.

0
source share

First of all, I will first back up your Python 2 file.

Then you can try to convert the code using the “2to3” tool with automatic conversion of Python code 2 to 3, which is built into Python through the standard library. Details on use can be found here: https://docs.python.org/2/library/2to3.html#

You also have a choice between two tools for automatically transferring your code: Upgrade and Futurization. Check them out below.

Upgrade -> https://python-modernize.readthedocs.io/en/latest/

Futurize → http://python-future.org/automatic_conversion.html

In terms of Pycharm, I have not seen / did not know a single specialized tool in the IDE that converts code from Python 2 to Python 3. I would stick to the three tools above.

Good luck

0
source share

To convert your python script from version-2 to version-3, you can simply use the 2to3 utility.

In a Linux terminal -

 $ 2to3 my_file.py # shows output only on terminal 

or

 $ 2to3 -w my_file.py # overwrites the file with python-3 code 

where my_file.py is the file you want to convert.

0
source share

All Articles