Python 2to3 for Converting Python 2 scripts to Python 3




Before concluding the Python 3 basics series, I think it would be wise to cover what can be involved when you run into code that is written in Python 2, as it will happen quite often and should be considered one of the basics to learning Python 3.

Generally, you will likely find the largest culprit for Python 2 code not working in Python 3 the Python 2 print statement, compared to the Python 3 print function.

print "Hello there"

The above is fine for Python 2, but will throw a syntax error in Python 3. That said, Python 2 code can also be:

print("Hello there")

Most Python 3 code is capable of running on Python 2.

Another major difference is going to be people's handling of exceptions. So in Python 2, you most often see:

try:
    dosomething
except Exception, e:
    return str(e)

This code will throw a syntax error in Python 3!

try:
    dosomething
except Exception as e:
    return str(e)

The above code is how Python 3 exceptions are supposed to be written, but this code also works as expected in Python 2.

The third major difference I find in Python 2 vs Python 3 coding is urllib and general internet access.

In Python 2, internet information is returned as string data. In Python 3, it comes in as bytes, and must be handled as such, being converted to string if that is how you wish to treat it.

There are quite a few other small things, but those are the main areas. For smaller scripts, these things can be usually fixed very quickly. For larger ones, however, it can get very tedious... very fast. Luckily, Python 3 comes with a script called 2to3, which converts quite a bit of common differences between Python 2 and Python 3 code.

For a quick example of 2to3 in action, let's write a quick Python 2 script:

import urllib2

try:
    x = urllib2.urlopen("http://pythonprogramming.net").read()
	print x
except Exception, e:
    print str(e)

The above code has a few things that need to be changed. First the import for urllib2 is not valid in Python 3, we just use urllib. Next, we use urllib2.urlopen to open the URL, which, again, is not valid. Then we print x like print is a statement. Python 3 sheds a tear at this point. Then we really kick Python 3 while it is down with the except Exception, e bit. Yikes. Then we finally just spit at Python 3 one last time with another print statement.

Now we're ready to test 2to3! Using this will vary slightly between operating systems. I show doing it in Windows and Ubuntu in the video. For the most part, however, you just need to reference the 2to3 script. The full path to it will be:

PythonDirectory / Tools / scripts / 2to3.py

Thus, on Windows, my version was in:

C:/Python34/Tools/scripts/2to3.py

You may be able to get by just typing 2to3, or python 2to3. Try if you like, didn't work for me since 2to3.py wasn't in my Path.

So, for me, I open up my cmd.exe to the directory that I saved our Python 2 file to. If you open cmd.exe to somewhere that isn't the directory that contains the python 2 script we just wrote, you need to change directory there (cd).

Now you can execute 2to3, here's what I typed:

C:/Python34/Tools/scripts/2to3.py python2script.py

That code will just output the problem and fixed code to the console. Now, let's actually convert the file!

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

With the additional -w (standing for write), we are able to write the changes to the file. You should also see a .bak file, which is a backup of the original file.

The next tutorial:






  • Python Introduction
  • Print Function and Strings
  • Math with Python
  • Variables Python Tutorial
  • While Loop Python Tutorial
  • For Loop Python Tutorial
  • If Statement Python Tutorial
  • If Else Python Tutorial
  • If Elif Else Python Tutorial
  • Functions Python Tutorial
  • Function Parameters Python Tutorial
  • Function Parameter Defaults Python Tutorial
  • Global and Local Variables Python Tutorial
  • Installing Modules Python Tutorial
  • How to download and install Python Packages and Modules with Pip
  • Common Errors Python Tutorial
  • Writing to a File Python Tutorial
  • Appending Files Python Tutorial
  • Reading from Files Python Tutorial
  • Classes Python Tutorial
  • Frequently asked Questions Python Tutorial
  • Getting User Input Python Tutorial
  • Statistics Module Python Tutorial
  • Module import Syntax Python Tutorial
  • Making your own Modules Python Tutorial
  • Python Lists vs Tuples
  • List Manipulation Python Tutorial
  • Multi-dimensional lists Python Tutorial
  • Reading CSV files in Python
  • Try and Except Error handling Python Tutorial
  • Multi-Line printing Python Tutorial
  • Python dictionaries
  • Built in functions Python Tutorial
  • OS Module Python Tutorial
  • SYS module Python Tutorial
  • Python urllib tutorial for Accessing the Internet
  • Regular Expressions with re Python Tutorial
  • How to Parse a Website with regex and urllib Python Tutorial
  • Tkinter intro
  • Tkinter buttons
  • Tkinter event handling
  • Tkinter menu bar
  • Tkinter images, text, and conclusion
  • Threading module
  • CX_Freeze Python Tutorial
  • The Subprocess Module Python Tutorial
  • Matplotlib Crash Course Python Tutorial
  • Python ftplib Tutorial
  • Sockets with Python Intro
  • Simple Port Scanner with Sockets
  • Threaded Port Scanner
  • Binding and Listening with Sockets
  • Client Server System with Sockets
  • Python 2to3 for Converting Python 2 scripts to Python 3
  • Python Pickle Module for saving Objects by serialization
  • Eval Module with Python Tutorial
  • Exec with Python Tutorial