Allow changing the name for a sequence in the sequence browser.
[mussa.git] / py / python.cpp
1 #include "py/python.hpp"
2
3 #include <iostream>
4
5 namespace py = boost::python;
6
7 MussaPython::MussaPython()
8 {
9   try {
10     // add our mussa module to our environment
11     PyImport_AppendInittab("mussa", &initmussa);
12     // go ahead and finish initalizing python
13     Py_Initialize();
14     // get reference to the global namespace
15     py::object main_module(
16         (py::handle<>(py::borrowed(PyImport_AddModule("__main__"))))
17     );
18     main_namespace = main_module.attr("__dict__");
19     // FIXME: this really should be a configuration file?
20     run("import __main__\n"
21         "import mussa\n"
22         "import webbrowser\n");
23   } catch (py::error_already_set e) {
24     PyErr_Print();
25   }
26 }
27
28 void MussaPython::run(std::string code)
29 {
30   try {
31     PyObject *global_ptr = main_namespace.ptr();
32     py::object result( py::handle<>(
33        (PyRun_String(code.c_str(), Py_file_input, global_ptr, global_ptr)
34     )));
35   } catch( py::error_already_set ) {
36     PyErr_Print();
37   }
38 }
39
40 py::object MussaPython::eval(std::string code)
41 {
42   try {
43     PyObject *global_ptr = main_namespace.ptr();
44     py::object result( py::handle<>(
45        (PyRun_String(code.c_str(), Py_eval_input, global_ptr, global_ptr)
46     )));
47     return result;
48   } catch( py::error_already_set ) {
49     PyErr_Print();
50   }
51   py::object result;
52   return  result;
53 }
54
55
56 void MussaPython::interpreter(FILE *fp)
57 {
58   try {
59     PyRun_InteractiveLoop(fp, "mussa");
60   } catch (py::error_already_set e) {
61     PyErr_Print();
62   }
63 }
64
65 py::object MussaPython::operator[](std::string name)
66
67   std::string code = "reduce(lambda m,n: m.__dict__[n], [__main__] + '";
68   code += name;
69   code += "'.split('.'))";
70   return eval(code);
71   /*
72   py::object py_name(name);
73   py::object name_list = py_name.attr("split")(".");
74   int name_list_len = extract<int>(name_list.attr("__len__")());
75   py::object lookup = main_namespace["__main__"];
76   for(int i=0; i < name_list_len; ++i) {
77     lookup = lookup.attr("__dict__")(name_list[i]);
78     //std::cout << lookup << std::endl;
79   }
80   return lookup;
81   */
82 }
83
84 //! return a reference to a single mussa python interpreter
85 MussaPython& get_py()
86 {
87   static MussaPython py;
88   return py;
89 }
90
91