Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert python 2 code to 3 in PyCharm

I have a large ML project in python 2 code and I just started using PyCharm as an IDE. I'm currently using WinPython 3.4 and I'd preferably like to do everything in python 3 instead of continue using legacy 2. When I cloned the project from git a popup in pycharm came up that was something along the lines of converting the code to 3 from 2 but I didn`t really think about it and exited it. How do I convert it?

like image 325
loag Avatar asked Jun 17 '16 22:06

loag


People also ask

How do I convert Python 2 to Python 3 code?

We can convert Python2 scripts to Python3 scripts by using 2to3 module. It changes Python2 syntax to Python3 syntax. We can change all the files in a particular folder from python2 to python3.

Can Python3 run Python 2 code?

Python 2.6 includes many capabilities that make it easier to write code that works on both 2.6 and 3. As a result, you can program in Python 2 but using certain Python 3 extensions... and the resulting code works on both.

How do I change Python version in Pycharm?

Change the Python interpreter in the project settingsPress Ctrl+Alt+S to open the IDE settings and select Project <project name> | Python Interpreter. Expand the list of the available interpreters and click the Show All link. Select the target interpreter.

How do I know if a script is Python 2 or 3?

If you want to determine whether Python2 or Python3 is running, you can check the major version with this sys. version_info. major . 2 means Python2, and 3 means Python3.


2 Answers

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

I applied in pycharm comunity edition v 2016.2.3 in windows environment.

  • click terminal in status bar Now, you are in shell command, in the root of your project.
  • type the command (to convert myfile.py):
2to3 myfile.py -w 

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

To modify all your files in the folder, type the command

2to3 . -w 

The option -w to actually write the changes. For more details write:

2to3 -h 
like image 104
M.Hassan Avatar answered Sep 29 '22 16:09

M.Hassan


Goto the folder where your python2script.py is existing in command line,

then execute the command:

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

you can see that your python2scipt.py is updated.

like image 20
letmecheck Avatar answered Sep 29 '22 14:09

letmecheck