Salome HOME
Merge branch 'master' into V9_dev
[modules/kernel.git] / src / Container / Container_init_python.cxx
1 // Copyright (C) 2007-2016  CEA/DEN, EDF R&D, OPEN CASCADE
2 //
3 // Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
5 //
6 // This library is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU Lesser General Public
8 // License as published by the Free Software Foundation; either
9 // version 2.1 of the License, or (at your option) any later version.
10 //
11 // This library is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 // Lesser General Public License for more details.
15 //
16 // You should have received a copy of the GNU Lesser General Public
17 // License along with this library; if not, write to the Free Software
18 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
19 //
20 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
21 //
22
23 #include <Python.h>
24 #include <structmember.h>
25 #ifndef WIN32
26   #include <sys/time.h>
27 #endif
28 #include <string>
29
30 #include "utilities.h"
31 #include "Container_init_python.hxx"
32
33 #if PY_VERSION_HEX < 0x03050000
34 static char*
35 Py_EncodeLocale(const wchar_t *arg, size_t *size)
36 {
37         return _Py_wchar2char(arg, size);
38 }
39 static wchar_t*
40 Py_DecodeLocale(const char *arg, size_t *size)
41 {
42         return _Py_char2wchar(arg, size);
43 }
44 #endif
45
46 /*
47   The following functions are used to hook the Python
48   interpreter output.
49 */
50
51 static void ContainerPyStdOut_dealloc(ContainerPyStdOut *self)
52 {
53   PyObject_Del(self);
54 }
55
56 static PyObject*
57 ContainerPyStdOut_write(ContainerPyStdOut *self, PyObject *args)
58 {
59   char *c;
60   if (!PyArg_ParseTuple(args, "s",&c))
61     return NULL;
62   if(self->_cb==NULL) {
63     if ( self->_iscerr )
64       std::cerr << c ;
65     else
66       std::cout << c ;
67   }
68   else {
69     self->_cb(self->_data,c);
70   }
71   Py_INCREF(Py_None);
72   return Py_None;
73 }
74
75 static PyObject*
76 ContainerPyStdOut_flush(ContainerPyStdOut *self)
77 {
78   Py_INCREF(Py_None);
79   return Py_None;
80 }
81
82 static PyMethodDef ContainerPyStdOut_methods[] = {
83   {"write",  (PyCFunction)ContainerPyStdOut_write,  METH_VARARGS, PyDoc_STR("write(string) -> None")},
84   {"flush",  (PyCFunction)ContainerPyStdOut_flush,  METH_NOARGS,  PyDoc_STR("flush() -> None")},
85   {NULL,    NULL}   /* sentinel */
86 };
87
88 static PyMemberDef ContainerPyStdOut_memberlist[] = {
89       {(char*)"softspace", T_INT,  offsetof(ContainerPyStdOut, softspace), 0,
90        (char*)"flag indicating that a space needs to be printed; used by print"},
91       {NULL} /* Sentinel */
92 };
93
94 static PyTypeObject ContainerPyStdOut_Type = {
95   /* The ob_type field must be initialized in the module init function
96    * to be portable to Windows without using C++. */
97   PyVarObject_HEAD_INIT(NULL, 0)
98   /*0,*/                                  /*ob_size*/
99   "PyOut",                                /*tp_name*/
100   sizeof(ContainerPyStdOut),              /*tp_basicsize*/
101   0,                                      /*tp_itemsize*/
102   /* methods */
103   (destructor)ContainerPyStdOut_dealloc,  /*tp_dealloc*/
104   0,                                      /*tp_print*/
105   0,                                      /*tp_getattr*/
106   0,                                      /*tp_setattr*/
107   0,                                      /*tp_compare*/
108   0,                                      /*tp_repr*/
109   0,                                      /*tp_as_number*/
110   0,                                      /*tp_as_sequence*/
111   0,                                      /*tp_as_mapping*/
112   0,                                      /*tp_hash*/
113   0,                                      /*tp_call*/
114   0,                                      /*tp_str*/
115   PyObject_GenericGetAttr,                /*tp_getattro*/
116  /* softspace is writable:  we must supply tp_setattro */
117   PyObject_GenericSetAttr,                /* tp_setattro */
118   0,                                      /*tp_as_buffer*/
119   Py_TPFLAGS_DEFAULT,                     /*tp_flags*/
120   0,                                      /*tp_doc*/
121   0,                                      /*tp_traverse*/
122   0,                                      /*tp_clear*/
123   0,                                      /*tp_richcompare*/
124   0,                                      /*tp_weaklistoffset*/
125   0,                                      /*tp_iter*/
126   0,                                      /*tp_iternext*/
127   ContainerPyStdOut_methods,              /*tp_methods*/
128   ContainerPyStdOut_memberlist,           /*tp_members*/
129   0,                                      /*tp_getset*/
130   0,                                      /*tp_base*/
131   0,                                      /*tp_dict*/
132   0,                                      /*tp_descr_get*/
133   0,                                      /*tp_descr_set*/
134   0,                                      /*tp_dictoffset*/
135   0,                                      /*tp_init*/
136   0,                                      /*tp_alloc*/
137   0,                                      /*tp_new*/
138   0,                                      /*tp_free*/
139   0,                                      /*tp_is_gc*/
140   0,                                      /*tp_bases*/
141   0,                                      /*tp_mro*/
142   0,                                      /*tp_cache*/
143   0,                                      /*tp_subclasses*/
144   0,                                      /*tp_weaklist*/
145   0,                                      /*tp_del*/
146   0,                                      /*tp_version_tag*/
147   0,                                      /*tp_finalize*/
148 };
149
150 static ContainerPyStdOut* ContainerNewPyStdOut( bool iscerr )
151 {
152   ContainerPyStdOut *self;
153   self = PyObject_New(ContainerPyStdOut, &ContainerPyStdOut_Type);
154   if (self == NULL)
155     return NULL;
156   self->softspace = 0;
157   self->_cb = NULL;
158   self->_iscerr = iscerr;
159   return self;
160 }
161
162 void KERNEL_PYTHON::init_python(int argc, char **argv)
163 {
164   if (Py_IsInitialized())
165     {
166       MESSAGE("Python already initialized");
167       return;
168     }
169   MESSAGE("=================================================================");
170   MESSAGE("Python Initialization...");
171   MESSAGE("=================================================================");
172   // set stdout to line buffering (aka C++ std::cout)
173   setvbuf(stdout, (char *)NULL, _IOLBF, BUFSIZ);
174   wchar_t* salome_python;
175   char* env_python=getenv("SALOME_PYTHON");
176   if(env_python != 0)
177     {
178       wchar_t* salome_python = Py_DecodeLocale(env_python, NULL);
179       Py_SetProgramName(salome_python);
180     }
181   Py_Initialize(); // Initialize the interpreter
182   if (Py_IsInitialized())
183     {
184       MESSAGE("Python initialized eh eh eh");
185     }
186   wchar_t **changed_argv = new wchar_t*[argc]; // Setting arguments
187   for (int i = 0; i < argc; i++)
188   {
189     changed_argv[i] = Py_DecodeLocale(argv[i], NULL);
190   }
191   PySys_SetArgv(argc, changed_argv);
192
193   PyRun_SimpleString("import threading\n");
194   // VSR (22/09/2016): This is a workaround to prevent invoking qFatal() from PyQt5
195   // causing application aborting
196   std::string script;
197   script += "def _custom_except_hook(exc_type, exc_value, exc_traceback):\n";
198   script += "  import sys\n";
199   script += "  sys.__excepthook__(exc_type, exc_value, exc_traceback)\n";
200   script += "  pass\n";
201   script += "\n";
202   script += "import sys\n";
203   script += "sys.excepthook = _custom_except_hook\n";
204   script += "del _custom_except_hook, sys\n";
205   int res = PyRun_SimpleString(script.c_str());
206   // VSR (22/09/2016): end of workaround
207   PyEval_InitThreads(); // Create (and acquire) the interpreter lock
208
209   // Create python objects to capture stdout and stderr
210   PyObject* _vout=(PyObject*)ContainerNewPyStdOut( false ); // stdout
211   PyObject* _verr=(PyObject*)ContainerNewPyStdOut( true );  // stderr
212   PySys_SetObject((char*)"stderr",_verr);
213   PySys_SetObject((char*)"stdout",_vout);
214
215   PyThreadState *pts = PyGILState_GetThisThreadState(); 
216   PyEval_ReleaseThread(pts);
217   //delete[] changed_argv;
218 }