summaryrefslogtreecommitdiff
path: root/python.h
blob: 7faefa0d78ae011a3c716532704b6988cf05e402 (plain)
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
#ifndef _PYTHON_H
#define _PYTHON_H

#include <boost/python.hpp>

using namespace boost::python;

namespace ledger {

struct python_support
{
  handle<> main_module;
  dict     main_namespace;

  python_support()
    : main_module(borrowed(PyImport_AddModule("__main__"))),
      main_namespace(handle<>(borrowed(PyModule_GetDict(main_module.get()))))
  {}
  ~python_support() {
  }
};

extern python_support * python_interpretor;

void init_python();

inline void python_eval(std::istream& in)
{
  if (! python_interpretor)
    init_python();

  std::string buffer;
  buffer.reserve(4096);
  while (! in.eof()) {
    char buf[256];
    in.getline(buf, 255);
    if (buf[0] == '!')
      break;
    buffer += buf;
    buffer += "\n";
  }

  try {
    handle<>(borrowed(PyRun_String(buffer.c_str(), Py_file_input,
				   python_interpretor->main_namespace.ptr(),
				   python_interpretor->main_namespace.ptr())));
  }
  catch(const boost::python::error_already_set&) {
    PyErr_Print();
  }
}

} // namespace ledger

#endif // _PYTHON_H