import_.cpp 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. // Copyright Stefan Seefeld 2007.
  2. // Distributed under the Boost Software License, Version 1.0. (See
  3. // accompanying file LICENSE_1_0.txt or copy at
  4. // http://www.boost.org/LICENSE_1_0.txt)
  5. #include <boost/python.hpp>
  6. #include <boost/detail/lightweight_test.hpp>
  7. #include <boost/bind.hpp>
  8. #include <iostream>
  9. #include <sstream>
  10. namespace bpl = boost::python;
  11. void import_test(char const *py_file_path)
  12. {
  13. // Retrieve the main module
  14. bpl::object main = bpl::import("__main__");
  15. // Retrieve the main module's namespace
  16. bpl::object global(main.attr("__dict__"));
  17. // Inject search path for import_ module
  18. bpl::str script(
  19. "import sys, os.path\n"
  20. "path = os.path.dirname(%r)\n"
  21. "sys.path.insert(0, path)"
  22. % bpl::str(py_file_path));
  23. bpl::object result = bpl::exec(script, global, global);
  24. // Retrieve the main module
  25. bpl::object import_ = bpl::import("import_");
  26. int value = bpl::extract<int>(import_.attr("value")) BOOST_EXTRACT_WORKAROUND;
  27. std::cout << value << std::endl;
  28. BOOST_TEST(value == 42);
  29. }
  30. int main(int argc, char **argv)
  31. {
  32. BOOST_TEST(argc == 2);
  33. // Initialize the interpreter
  34. Py_Initialize();
  35. if (bpl::handle_exception(boost::bind(import_test,argv[1])))
  36. {
  37. if (PyErr_Occurred())
  38. {
  39. BOOST_ERROR("Python Error detected");
  40. PyErr_Print();
  41. }
  42. else
  43. {
  44. BOOST_ERROR("A C++ exception was thrown for which "
  45. "there was no exception handler registered.");
  46. }
  47. }
  48. // Boost.Python doesn't support Py_Finalize yet.
  49. // Py_Finalize();
  50. return boost::report_errors();
  51. }
  52. // Including this file makes sure
  53. // that on Windows, any crashes (e.g. null pointer dereferences) invoke
  54. // the debugger immediately, rather than being translated into structured
  55. // exceptions that can interfere with debugging.
  56. #include "module_tail.cpp"