C++ to Python?

Tom Plunket tomas at fancy.org
Wed Oct 11 02:48:02 CEST 2006


Roman Yakovenko wrote:

> you want to find some kind of "translator"
> 
> C++ code:
>    std::cout << 1;
> translator output:
>    print 1
> 
> Am I right? If so, I am pretty sure that such "translator" does not
> exist - too complex.

...however such a "refactor" is easy for a human to do.

What the OP could do is read up on wrapping the C++ API, and then do
the "change language refactor" incrementally per source file.  Even
for a large application, if you had the whole C++ API wrapped so it
was accessible via Python, it'd be fairly straight-forward and perhaps
even easy.  Heck, you could even write a quickie conversion utility
that converted the top-level C++ syntax into Python syntax to get 90%
of the way there.

Even a quickie:

def ConvertBraces(filename):
   lines = file(filename).readlines()

   indent = 0

   for line in lines:
      stripped = line.strip()
      if stripped == '{':
         indent += 1
         print ':',
      elif stripped == '}':
         indent -= 1
         print '\n', '\t'*indent, 'pass\n'
      elif:
         print '\n', '\t'*indent, stripped

files = glob.glob('*.cpp')

for f in files:
   ConvertBraces(f)

...that may well get you started.  ;)

For fancy stuff like comment matching I'll suggest the re library.

-tom!



More information about the Python-list mailing list