I am currently working on adding embedded Python support (and yes, extending is not an option) to a large program as part of my summer internship. Ideally, I can keep the Python support within a single .DLL, which currently contains the program's in-house scripting language and is the easiest place to integrate said language and Python.
However, due to the program's API, I only have a single input function to use. This function's return value is a single line from the current input, which could be the console or a file. The input interface cannot (within the .DLL) be converted into a stream object, buffer, or FILE pointer.
My current test code (written outside of the program, using std::string, istream, and getline to ape the restriction) is
// start python
Py_Initialize();
try
{
cout << "Python " << Py_GetVersion() << endl;
string block;
bool in_block = false;
while ( !cin.eof() )
{
string str;
cout << (in_block ? "... " : ">>> "); // prompt string
getline(cin,str);
if ( in_block ) // if in an indented block
{
if ( str.front() != ' ' && str.front() != '\t' ) // if ending the indented block
{
PyRun_SimpleString(block.c_str()); // run Python code contained in block string
block.clear(); // clear string for next block
in_block = false; // no longer in block
}
else // a component of an indented block
{
block += (str+'\n'); // append input to block string
continue; // do not pass block exit code, do not collect two hundred dollars
}
}
// either not in an indented block, or having just come out of one
if ( str.back() == ':' ) // if colon, start new indented block
{
block = (str+'\n');
in_block = true;
continue;
}
else { PyRun_SimpleString(str.c_str()); } // otherwise, run block-free code
}
}
catch ( error_already_set e ) { PyErr_Print(); }
// close python
Py_Finalize();
// done
return 0;
I have not encountered serious problems with this hack, but it strikes me as woefully inelegant. Can anyone think of a better way to do this?
I have already cleared the boost.python libraries with my boss, if that offers some useful trick that eluded me.
EDIT: I should probably mention the program itself, while not my meagre testbed, must run on MS Windows.