[Tutor] regex to promote Py 2 to Py 3?
eryksun
eryksun at gmail.com
Wed Apr 17 04:24:08 CEST 2013
On Tue, Apr 16, 2013 at 9:02 PM, Jim Mooney <cybervigilante at gmail.com> wrote:
> So for online progs, examples, ebooks, etc, that still have Py 2
> examples I can copy, has anyone come up with a nice regex package to
> do most of the conversions and produce a mostly Py3 from a Py2? That
> might make some things a bit easier.
Generally the 2to3 script does an OK job. If you're using Windows it's
[Python_Dir]\Tools\Scripts\2to3.py.
http://docs.python.org/3/library/2to3
lib2to3 doesn't have a stable API, but you can use it in the REPL if
you want to experiment:
>>> from lib2to3.refactor import RefactoringTool
>>> rt = RefactoringTool(['lib2to3.fixes.fix_print'])
>>> code2 = r'''
... for s in strings:
... print >>myfile, s,
... '''
>>> code3 = str(rt.refactor_string(code2, '<string>'))
>>> print(code3)
for s in strings:
print(s, end=' ', file=myfile)
If you want all the fixes applied, you can use
>>> from lib2to3.refactor import (
... RefactoringTool, get_fixers_from_package)
>>> rt = RefactoringTool(get_fixers_from_package('lib2to3.fixes'))
>>> code2 = r'''
... class Test(object):
... __metaclass__ = MetaTest
... '''
>>> code3 = str(r.refactor_string(code2, '<string>'))
>>> print(code3)
class Test(object, metaclass=MetaTest):
pass
More information about the Tutor
mailing list