ScriptingEngine.cpp 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. #include <Python.h>
  2. #include "ScriptingEngine.h"
  3. #include "Exception.h"
  4. #include "Logger.h"
  5. #include "Globals.h"
  6. extern "C" void initAnki(); /// Defined in BoostPythonInterfaces.cpp by boost::python
  7. //======================================================================================================================
  8. // init =
  9. //======================================================================================================================
  10. void ScriptingEngine::init()
  11. {
  12. INFO("Initializing scripting engine...");
  13. PyImport_AppendInittab((char*)("Anki"), &initAnki);
  14. Py_Initialize();
  15. mainModule = boost::python::object(boost::python::handle<>(boost::python::borrowed(PyImport_AddModule("__main__"))));
  16. mainNamespace = mainModule.attr("__dict__");
  17. ankiModule = boost::python::object(boost::python::handle<>(PyImport_ImportModule("Anki")));
  18. INFO("Scripting engine initialized");
  19. }
  20. //======================================================================================================================
  21. // execScript =
  22. //======================================================================================================================
  23. void ScriptingEngine::execScript(const char* script, const char* scriptName)
  24. {
  25. try
  26. {
  27. boost::python::handle<>ignored(PyRun_String(script, Py_file_input, mainNamespace.ptr(), mainNamespace.ptr()));
  28. }
  29. catch(boost::python::error_already_set)
  30. {
  31. PyErr_Print();
  32. throw EXCEPTION("Script \"" + scriptName + "\" failed with error");
  33. }
  34. }