File: import_.cpp

package info (click to toggle)
boost 1.34.1-14
  • links: PTS
  • area: main
  • in suites: lenny
  • size: 116,412 kB
  • ctags: 259,566
  • sloc: cpp: 642,395; xml: 56,450; python: 17,612; ansic: 14,520; sh: 2,265; yacc: 858; perl: 481; makefile: 478; lex: 94; sql: 74; csh: 6
file content (66 lines) | stat: -rw-r--r-- 1,851 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
// Copyright Stefan Seefeld 2007.
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)

#include <boost/python.hpp>
#include <boost/bind.hpp>
#include <boost/detail/lightweight_test.hpp>
#include <iostream>
#include <sstream>

namespace bpl = boost::python;

void import_test( char** argv )
{
  // Retrieve the main module
  bpl::object main = bpl::import("__main__");
  
  // Retrieve the main module's namespace
  bpl::object global(main.attr("__dict__"));

  // Inject search path for import_ module
  std::ostringstream script;
  script << "import sys, os\n"
         << "path = os.path.dirname('" << argv[1] << "')\n"
         << "sys.path.insert(0, path)\n";
  bpl::exec(bpl::str(script.str()), global, global);
  
  // Retrieve the main module
  bpl::object import_ = bpl::import("import_");
  int value = bpl::extract<int>(import_.attr("value")) BOOST_EXTRACT_WORKAROUND;
  std::cout << value << std::endl;
  BOOST_TEST(value == 42);
}

int main(int argc, char **argv)
{
  BOOST_TEST(argc == 2);

  // Initialize the interpreter
  Py_Initialize();
  
  if (bpl::handle_exception(boost::bind(import_test, argv)))
  {
    if (PyErr_Occurred())
    {
      BOOST_ERROR("Python Error detected");
      PyErr_Print();
    }
    else
    {
        BOOST_ERROR("A C++ exception was thrown  for which "
                    "there was no exception handler registered.");
    }
  }
    
  // Boost.Python doesn't support Py_Finalize yet.
  // Py_Finalize();
  return boost::report_errors();
}

// Including this file makes sure
// that on Windows, any crashes (e.g. null pointer dereferences) invoke
// the debugger immediately, rather than being translated into structured
// exceptions that can interfere with debugging.
#include "module_tail.cpp"