Flow123d
python_loader.hh
Go to the documentation of this file.
1 /*
2  * python_utils.hh
3  *
4  * Created on: Aug 31, 2012
5  * Author: jb
6  */
7 
8 #ifndef PYTHON_UTILS_HH_
9 #define PYTHON_UTILS_HH_
10 
11 #ifdef HAVE_PYTHON
12 
13 #include "Python.h"
14 #include <string>
15 
16 
17 namespace internal {
18 /**
19  * Class to implement initialization and finalization of the python module
20  */
21 class PythonRunning {
22 public:
23  PythonRunning();
24  ~PythonRunning();
25 };
26 } // close namespace internal
27 
28 
29 
30 /**
31  * Class with static only members, should be used to load and compile Python sources either from file or from string.
32  * Implement correct initialization and finalization.
33  * TODO:
34  * - check validity of results and throw exceptions
35  * - better loading of modules from files
36  * - explain and resolve RuntimeWarning:
37  * "flow123d_python_loader:1: RuntimeWarning: Parent module 'field_python_script' not found while handling absolute import"
38  * that appears during field_python_test.cpp
39  *
40  */
41 class PythonLoader {
42 public:
43  PythonLoader();
44  /**
45  * This function loads a module from the given file.
46  * Resulting module has to be deallocated by Py_DECREF() macro.
47  */
48  static PyObject * load_module_from_file(const std::string& fname);
49  /**
50  * This function compile code in the given string and creates a module with name @p module_name.
51  * Resulting module has to be deallocated by Py_DECREF() macro.
52  */
53  static PyObject * load_module_from_string(const std::string& module_name, const std::string& source_string);
54 
55 protected:
56  // implements automatic initialization and finalization
57  static internal::PythonRunning py_running;
58 };
59 
60 
61 
62 #endif // HAVE_PYTHON
63 
64 #endif /* PYTHON_UTILS_HH_ */