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