Convert Python 2.x Scripts to Python 3.x Scripts

As we have all already know that, Python 3 can not run Python 2 scripts correctly as it throws lots of syntax error.So if you want to convert Python 2.x scripts in Python 3.x interpreter , here is the solution of How To

Convert Python 2.x Scripts to Python 3.x Scripts

Python 3.x comes with a built-in library/module called 2to3 , that convert your Python 2.x scripts to Python 3.x scripts by typing one or two lines in command shell.

  • Here is the script written in Python 2.x [Linux/Ubuntu], which is in my Desktop, i named it as p2script.py and change my root directory to Desktop i.e cd Desktop
  • www.pythonlovers.net/ convert-python-2-x-scripts-to-python-3-x-scripts
  • When i run this script with Python 2.x interpreter its show the correct output
    [Note: In command prompt or terminal type “python” for using Python 2.x interpreter and type “python3” for using Python 3.x interpreter]
  • www.pythonlovers.net/ convert-python-2-x-scripts-to-python-3-x-scriptswww.pythonlovers.net/ convert-python-2-x-scripts-to-python-3-x-scriptswww.pythonlovers.net/ convert-python-2-x-scripts-to-python-3-x-scripts
  • But When i run this script with Python 3.x interpreter its show the errors
  • www.pythonlovers.net/ convert-python-2-x-scripts-to-python-3-x-scripts
  • So in order to run script in Python 3.x,we have to convert it into Python 3 script
  • To do that we use the command “2to3” script in terminal window ,it’ll let you know the exact alternative code for your Python 3 scripts as given in below image .just type–> 2to3 p2script.py
  • www.pythonlovers.net/ convert-python-2-x-scripts-to-python-3-x-scripts
  • But we have to convert it automatically instead of writting or changing each lines of code,to do this type in your terminal window –> 2to3 -w p2script.py
    (where p2script is the name of my script,you can write the name of your script you want to convert).
  • www.pythonlovers.net/ convert-python-2-x-scripts-to-python-3-x-scriptswww.pythonlovers.net/ convert-python-2-x-scripts-to-python-3-x-scripts
  • Now open your script in any editor,you will see that your script automatically got changed
  • www.pythonlovers.net/ convert-python-2-x-scripts-to-python-3-x-scripts
  • Now try to run your newly modified script in Python 3.x interpreter
  • www.pythonlovers.net/ convert-python-2-x-scripts-to-python-3-x-scriptswww.pythonlovers.net/ convert-python-2-x-scripts-to-python-3-x-scripts

Cheers we successfully Convert Python 2.x Scripts to Python 3.x Scripts.
For more Information on “urllib module” please refer our post on this site “How To Retrive Data From Internet In Python” OR visit official
For urllib2 in Python2.x https://docs.python.org/2/library/urllib2.html
For urllib in Python 3.x https://docs.python.org/3.5/library/urllib.html