Saturday, July 15, 2006

A Random Tip for Embedding Python

I learned this one the hard way. I'm working on a simulator, written in C++ and using embedded Python for the interpreter. It works great, except that the arrow keys spew escape codes rather than allowing line or history editing.

I poured through Extending and Embedding the Python Interpreter. An afternoon of searching on google turned up nothing. I looked for "embedded python," "arrow keys," "readline," "escape codes," and anything else I could think of in varying combinations.

The solution was ultimately to RTFS. I downloaded the source for the version on the machine I have at work (2.2.3) and the latest release (2.4.3). The solution, found in Py_Main() in the latter, was to import the readline module in my own program before calling PyRun_InteractiveLoop().

It's simple enough, and perfectly sensible. Why the hell couldn't it be mentioned in the documentation, though?

In any event, hopefully by posting this here I will have made life a little easier for the next poor soul who finds himself googling for how to get the arrow keys to work in embedded Python.

No comments: