Flow123d  jenkins-Flow123d-windows32-release-multijob-51
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(const std::string &python_home);
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 
44  /**
45  * Calls python initialization and guarantee that appropriate finalization will be called.
46  * Do nothing if initialization was done.
47  *
48  * The method with no parameters is called at the beginning of every function of this class, so an explicit call
49  * to it has only sense if one would like to provide alternative python home directories.
50  * The string has form <prefix>[:<exec_prefix>] where <prefix> is prefix for platform independent libraries
51  * (namely sources of python standard libraries) and <exec_prefix> is prefix for platform dependent libraries namely
52  * for the python executable.
53  */
54 
55  static void initialize(const std::string &python_home="");
56 
57  /**
58  * This function loads a module from the given file.
59  * Resulting module has to be deallocated by Py_DECREF() macro.
60  */
61  static PyObject * load_module_from_file(const std::string& fname);
62  /**
63  * This function compile code in the given string and creates a module with name @p module_name.
64  * Resulting module has to be deallocated by Py_DECREF() macro.
65  */
66  static PyObject * load_module_from_string(const std::string& module_name, const std::string& source_string);
67 };
68 
69 
70 
71 #endif // HAVE_PYTHON
72 
73 #endif /* PYTHON_UTILS_HH_ */