Salome HOME
Updated copyright comment
[modules/kernel.git] / src / Container / Container_init_python.cxx
1 // Copyright (C) 2007-2024  CEA, EDF, 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*/, PyObject */*args*/)
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   {0, 0, 0, 0} /* sentinel */
86 };
87
88 static PyMemberDef ContainerPyStdOut_memberlist[] = {
89   {(char*)"softspace", T_INT,  offsetof(ContainerPyStdOut, softspace), 0, (char*)"flag indicating that a space needs to be printed; used by print"},
90   {0, 0, 0, 0, 0} /* sentinel */
91 };
92
93 static PyTypeObject ContainerPyStdOut_Type = {
94   /* The ob_type field must be initialized in the module init function
95    * to be portable to Windows without using C++. */
96   PyVarObject_HEAD_INIT(NULL, 0)
97   /*0,*/                                  /*ob_size*/
98   "PyOut",                                /*tp_name*/
99   sizeof(ContainerPyStdOut),              /*tp_basicsize*/
100   0,                                      /*tp_itemsize*/
101   /* methods */
102   (destructor)ContainerPyStdOut_dealloc,  /*tp_dealloc*/
103   0,                                      /*tp_print*/
104   0,                                      /*tp_getattr*/
105   0,                                      /*tp_setattr*/
106   0,                                      /*tp_compare*/
107   0,                                      /*tp_repr*/
108   0,                                      /*tp_as_number*/
109   0,                                      /*tp_as_sequence*/
110   0,                                      /*tp_as_mapping*/
111   0,                                      /*tp_hash*/
112   0,                                      /*tp_call*/
113   0,                                      /*tp_str*/
114   PyObject_GenericGetAttr,                /*tp_getattro*/
115  /* softspace is writable:  we must supply tp_setattro */
116   PyObject_GenericSetAttr,                /* tp_setattro */
117   0,                                      /*tp_as_buffer*/
118   Py_TPFLAGS_DEFAULT,                     /*tp_flags*/
119   0,                                      /*tp_doc*/
120   0,                                      /*tp_traverse*/
121   0,                                      /*tp_clear*/
122   0,                                      /*tp_richcompare*/
123   0,                                      /*tp_weaklistoffset*/
124   0,                                      /*tp_iter*/
125   0,                                      /*tp_iternext*/
126   ContainerPyStdOut_methods,              /*tp_methods*/
127   ContainerPyStdOut_memberlist,           /*tp_members*/
128   0,                                      /*tp_getset*/
129   0,                                      /*tp_base*/
130   0,                                      /*tp_dict*/
131   0,                                      /*tp_descr_get*/
132   0,                                      /*tp_descr_set*/
133   0,                                      /*tp_dictoffset*/
134   0,                                      /*tp_init*/
135   0,                                      /*tp_alloc*/
136   0,                                      /*tp_new*/
137   0,                                      /*tp_free*/
138   0,                                      /*tp_is_gc*/
139   0,                                      /*tp_bases*/
140   0,                                      /*tp_mro*/
141   0,                                      /*tp_cache*/
142   0,                                      /*tp_subclasses*/
143   0,                                      /*tp_weaklist*/
144   0,                                      /*tp_del*/
145   0,                                      /*tp_version_tag*/
146   0,                                      /*tp_finalize*/
147 };
148
149 static ContainerPyStdOut* ContainerNewPyStdOut( bool iscerr )
150 {
151   ContainerPyStdOut *self;
152   self = PyObject_New(ContainerPyStdOut, &ContainerPyStdOut_Type);
153   if (self == NULL)
154     return NULL;
155   self->softspace = 0;
156   self->_cb = NULL;
157   self->_iscerr = iscerr;
158   return self;
159 }
160
161 void KERNEL_PYTHON::init_python(int argc, char **argv)
162 {
163   if (Py_IsInitialized())
164     {
165       MESSAGE("Python already initialized");
166       return;
167     }
168   // set stdout to line buffering (aka C++ std::cout)
169   setvbuf(stdout, (char *)NULL, _IOLBF, BUFSIZ);
170   char* env_python=getenv("SALOME_PYTHON");
171   if(env_python != 0)
172     {
173       wchar_t* salome_python = Py_DecodeLocale(env_python, NULL);
174       Py_SetProgramName(salome_python);
175     }
176   Py_Initialize(); // Initialize the interpreter
177   if (Py_IsInitialized())
178     {
179       MESSAGE("Python initialized");
180     }
181   wchar_t **changed_argv = new wchar_t*[argc]; // Setting arguments
182   for (int i = 0; i < argc; i++)
183   {
184     changed_argv[i] = Py_DecodeLocale(argv[i], NULL);
185   }
186   PySys_SetArgv(argc, changed_argv);
187
188   PyRun_SimpleString("import threading\n");
189   // VSR (22/09/2016): This is a workaround to prevent invoking qFatal() from PyQt5
190   // causing application aborting
191   std::string script;
192   script += "def _custom_except_hook(exc_type, exc_value, exc_traceback):\n";
193   script += "  import sys\n";
194   script += "  sys.__excepthook__(exc_type, exc_value, exc_traceback)\n";
195   script += "  pass\n";
196   script += "\n";
197   script += "import sys\n";
198   script += "sys.excepthook = _custom_except_hook\n";
199   script += "del _custom_except_hook, sys\n";
200   PyRun_SimpleString(script.c_str());
201   // VSR (22/09/2016): end of workaround
202 #if PY_VERSION_HEX < 0x03070000
203   PyEval_InitThreads(); // Create (and acquire) the interpreter lock
204 #endif
205   // Create python objects to capture stdout and stderr
206   PyObject* _vout=(PyObject*)ContainerNewPyStdOut( false ); // stdout
207   PyObject* _verr=(PyObject*)ContainerNewPyStdOut( true );  // stderr
208   PySys_SetObject((char*)"stderr",_verr);
209   PySys_SetObject((char*)"stdout",_vout);
210
211   PyThreadState *pts = PyGILState_GetThisThreadState(); 
212   PyEval_ReleaseThread(pts);
213   //delete[] changed_argv;
214 }