3

I have written a small Qt-based text editor for Python code that I embed in my application. Now I am going to switch to Python 3 and I want to help the users of my app with converting their code. I know that 2to3 can do most of the conversion for files. However, I need an on-the-fly conversion, without touching the files on disk. I mean something like:

py3_code_str = convert2to3(py2_code_str)

Does anybody know how it can be achieved with 2to3 or lib2to3?

Maciek D.
  • 2,754
  • 1
  • 20
  • 17
  • I guess the best workaround would be to write the string into a temporary file (with help of the tempfile module), apply 2to3 and read the content of the file back into your self-written editor. – elzell Dec 16 '15 at 09:02

3 Answers3

3

Unfortunately, lib2to3 doesn't have stable interface, meaning it might change drastically.

Though, in case you don't really care about that, it might be possible (with minor changes) to use from lib2to3.refactor import RefactoringTool and continue on with its refactor_string method.

plaes
  • 31,788
  • 11
  • 91
  • 89
3

What worked for me thanks to plaes answer:

from lib2to3.refactor import RefactoringTool, get_fixers_from_package
refactoring_tool = RefactoringTool(fixer_names=get_fixers_from_package('lib2to3.fixes'))
node3 = refactoring_tool.refactor_string(text2, 'script')
text3 = str(node3)
Community
  • 1
  • 1
Maciek D.
  • 2,754
  • 1
  • 20
  • 17
-1

That's really not what 2to3 is for.

You should be writing your code in such a way that it is compatible with both Python 2 and 3. The six library can help with that.

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895