Using to to convert the code

After you've fixed any warnings from running the code with the -3 parameter under Python 2.6 or higher, the next step is to run the 2to3 tool on it to produce a version for Python 3. 2to3 will make a number of automatic fixes, things like changing raw_input to input, print to print(), and so on, but it's unlikely that the converted code will run without error.

The 2to3 tool takes either a file or a directory to convert and generates a patch file of all the changes to be applied to convert to Python 3. If it's unable to apply a fix for a problem automatically, it prints a warning below the diff for that file. By default, 2to3 runs several fixers and more can be added; running 2to3 -l (that's a lowercase "el") will show what fixers are available. If you want to exclude a particular fixer, using the -x option followed by the fixer name will exclude it, as in the following example where the has_key fixer is turned off:

[email protected]:~$ 2to3 -x has_key convert2_3.py

Using the -f option turns on fixers explicitly, with all enabling all the default fixers, whereas using the fixer name enables only the fixer mentioned. If we want to enable only the has_key fixer, we use [email protected]:~$ 2to3 -f has_key convert2_3.py

And if we want to enable all the default fixers and the apply fixer, the command is [email protected]:~$ 2to3 -f all -f apply convert2_3.py

Running 2to3 on our sample file gives us the diff in listing 22.2.

Listing 22.2 File convert2_3.diff

outfile.write(data) outfile.close()

- except StandardError, e:

def read_file(filename):

infile = file(filename, "rb") @@ -19,24 +19,24 @@

major_version = int(file_version[0]) minor_version = int(file_version[2])

- if major_version <> 1 or minor_version > 5:

- raise Exception, "Wrong file version"

+ if major_version != 1 or minor_version > 5: + raise Exception("Wrong file version")

infile.close()

return file_version, data if _name_ == "_main_":

- filename = raw_input("Please enter a filename: ") + filename = input("Please enter a filename: ")

write_file(filename, version, "this is test data")

- print "File created, reading data from file" + print("File created, reading data from file")

new_version, data = read_file(filename)

quarters = cents / 25

- print "%s cents contains %s quarters" % (cents, + print("%s cents contains %s quarters" % (cents, new_dict = {}

- if not new_dict.has_key(new_version): + if new_version not in new_dict:

new_dict[new_version] = filename

We can use a patch tool to apply the changes to our source, or we can use 2to3's -w option to automatically write the changes back to the file while creating a backup copy of the original.

Was this article helpful?

0 0

Post a comment