This example demonstrates how to use Graph-sitter to automatically migrate Python 2 code to Python 3. For a complete walkthrough, check out our tutorial.
The migration script handles five key transformations:
-
Convert Print Statements
# From: print "Hello, world!" print x, y, z # To: print("Hello, world!") print(x, y, z)
-
Update Unicode to str
# From: from __future__ import unicode_literals text = unicode("Hello") prefix = "prefix" # To: text = str("Hello") prefix = "prefix"
-
Convert raw_input to input
# From: name = raw_input("Enter your name: ") # To: name = input("Enter your name: ")
-
Update Exception Handling
# From: try: process_data() except ValueError, e: print(e) # To: try: process_data() except ValueError as e: print(e)
-
Modernize Iterator Methods
# From: class MyIterator: def next(self): return self.value # To: class MyIterator: def __next__(self): return self.value
# Install Graph-sitter
pip install graph-sitter
# Run the migration
python run.pyThe script will process all Python files in the repo-before directory and apply the transformations in the correct order.
run.py- The migration scriptinput_repo/- Sample Python 2 code to migrate