xref: /petsc/src/sys/python/pythonsys.c (revision 98d129c30f3ee9fdddc40fdbc5a989b7be64f888)
1 #include <petsc/private/petscimpl.h> /*I "petscsys.h" I*/
2 
3 #if !defined(PETSC_PYTHON_EXE)
4   #define PETSC_PYTHON_EXE "python"
5 #endif
6 
7 static PetscErrorCode PetscPythonFindExecutable(char pythonexe[], size_t len)
8 {
9   PetscBool flag;
10 
11   PetscFunctionBegin;
12   /* get the path for the Python interpreter executable */
13   PetscCall(PetscStrncpy(pythonexe, PETSC_PYTHON_EXE, len));
14   PetscCall(PetscOptionsGetString(NULL, NULL, "-python", pythonexe, len, &flag));
15   if (!flag || pythonexe[0] == 0) PetscCall(PetscStrncpy(pythonexe, PETSC_PYTHON_EXE, len));
16   PetscFunctionReturn(PETSC_SUCCESS);
17 }
18 
19 /*
20     Python does not appear to have a universal way to indicate the location of Python dynamic library so try several possibilities
21 */
22 static PetscErrorCode PetscPythonFindLibraryName(const char pythonexe[], const char attempt[], char pythonlib[], size_t pl, PetscBool *found)
23 {
24   char  command[2 * PETSC_MAX_PATH_LEN];
25   FILE *fp  = NULL;
26   char *eol = NULL;
27 
28   PetscFunctionBegin;
29   /* call Python to find out the name of the Python dynamic library */
30   PetscCall(PetscStrncpy(command, pythonexe, sizeof(command)));
31   PetscCall(PetscStrlcat(command, " ", sizeof(command)));
32   PetscCall(PetscStrlcat(command, attempt, sizeof(command)));
33 #if defined(PETSC_HAVE_POPEN)
34   PetscCall(PetscPOpen(PETSC_COMM_SELF, NULL, command, "r", &fp));
35   PetscCheck(fgets(pythonlib, pl, fp), PETSC_COMM_SELF, PETSC_ERR_PLIB, "Python: bad output from executable: %s, running: %s", pythonexe, command);
36   PetscCall(PetscPClose(PETSC_COMM_SELF, fp));
37 #else
38   SETERRQ(PETSC_COMM_SELF, PETSC_ERR_LIB, "Python: Aborted due to missing popen()");
39 #endif
40   /* remove newlines */
41   PetscCall(PetscStrchr(pythonlib, '\n', &eol));
42   if (eol) eol[0] = 0;
43   PetscCall(PetscTestFile(pythonlib, 'r', found));
44   PetscFunctionReturn(PETSC_SUCCESS);
45 }
46 
47 static PetscErrorCode PetscPythonFindLibrary(const char pythonexe[], char pythonlib[], size_t pl)
48 {
49   // clang-format off
50   const char *const cmdlines[] = {"-c 'import os, sysconfig; print(os.path.join(sysconfig.get_config_var(\"LIBDIR\"),sysconfig.get_config_var(\"LDLIBRARY\")))'",
51                                   "-c 'import os, sysconfig; print(os.path.join(sysconfig.get_path(\"stdlib\"),os.path.pardir,\"libpython\"+sysconfig.get_python_version()+\".dylib\"))'",
52                                   "-c 'import os, sysconfig; print(os.path.join(sysconfig.get_path(\"stdlib\"),os.path.pardir,\"libpython\"+sysconfig.get_python_version()+\".so\"))'",
53                                   "-c 'import os, sysconfig; print(os.path.join(sysconfig.get_config_var(\"LIBPL\"),sysconfig.get_config_var(\"LDLIBRARY\")))'",
54                                   "-c 'import sysconfig; print(sysconfig.get_config_var(\"LIBPYTHON\"))'",
55                                   "-c 'import os, sysconfig; print(os.path.join(sysconfig.get_config_var(\"LIBDIR\"),\"libpython\"+sysconfig.get_python_version()+\".dylib\"))'",
56                                   "-c 'import os, sysconfig; print(os.path.join(sysconfig.get_config_var(\"LIBDIR\"),\"libpython\"+sysconfig.get_python_version()+\".so\"))'"};
57   // clang-format on
58 
59   PetscBool found = PETSC_FALSE;
60 
61   PetscFunctionBegin;
62 #if defined(PETSC_PYTHON_LIB)
63   PetscCall(PetscStrncpy(pythonlib, PETSC_PYTHON_LIB, pl));
64   PetscFunctionReturn(PETSC_SUCCESS);
65 #endif
66 
67   for (size_t i = 0; i < PETSC_STATIC_ARRAY_LENGTH(cmdlines); i++) {
68     PetscCall(PetscInfo(NULL, "Looking for Python library with \"%s %s\"\n", pythonexe, cmdlines[i]));
69     PetscCall(PetscPythonFindLibraryName(pythonexe, cmdlines[i], pythonlib, pl, &found));
70     if (found) break;
71   }
72   PetscCall(PetscInfo(NULL, "Python library %s found %d\n", pythonlib, found));
73   PetscFunctionReturn(PETSC_SUCCESS);
74 }
75 
76 typedef struct _Py_object_t PyObject; /* fake definition */
77 
78 static PyObject *Py_None = NULL;
79 
80 static const char *(*Py_GetVersion)(void);
81 
82 static int (*Py_IsInitialized)(void);
83 static void (*Py_InitializeEx)(int);
84 static void (*Py_Finalize)(void);
85 
86 static void (*PySys_SetArgv)(int, void *);
87 static PyObject *(*PySys_GetObject)(const char *);
88 static PyObject *(*PyObject_CallMethod)(PyObject *, const char *, const char *, ...);
89 static PyObject *(*PyImport_ImportModule)(const char *);
90 
91 static void (*Py_IncRef)(PyObject *);
92 static void (*Py_DecRef)(PyObject *);
93 
94 static void (*PyErr_Clear)(void);
95 static PyObject *(*PyErr_Occurred)(void);
96 static void (*PyErr_Fetch)(PyObject **, PyObject **, PyObject **);
97 static void (*PyErr_NormalizeException)(PyObject **, PyObject **, PyObject **);
98 static void (*PyErr_Display)(PyObject *, PyObject *, PyObject *);
99 static void (*PyErr_Restore)(PyObject *, PyObject *, PyObject *);
100 
101 #define PetscDLPyLibOpen(libname)      PetscDLLibraryAppend(PETSC_COMM_SELF, &PetscDLLibrariesLoaded, libname)
102 #define PetscDLPyLibSym(symbol, value) PetscDLLibrarySym(PETSC_COMM_SELF, &PetscDLLibrariesLoaded, NULL, symbol, (void **)value)
103 #define PetscDLPyLibClose(comm) \
104   do { \
105   } while (0)
106 
107 static PetscErrorCode PetscPythonLoadLibrary(const char pythonlib[])
108 {
109   PetscFunctionBegin;
110   /* open the Python dynamic library */
111   PetscCall(PetscDLPyLibOpen(pythonlib));
112   PetscCall(PetscInfo(NULL, "Python: loaded dynamic library %s\n", pythonlib));
113   /* look required symbols from the Python C-API */
114   PetscCall(PetscDLPyLibSym("_Py_NoneStruct", &Py_None));
115   PetscCall(PetscDLPyLibSym("Py_GetVersion", &Py_GetVersion));
116   PetscCall(PetscDLPyLibSym("Py_IsInitialized", &Py_IsInitialized));
117   PetscCall(PetscDLPyLibSym("Py_InitializeEx", &Py_InitializeEx));
118   PetscCall(PetscDLPyLibSym("Py_Finalize", &Py_Finalize));
119   PetscCall(PetscDLPyLibSym("PySys_GetObject", &PySys_GetObject));
120   PetscCall(PetscDLPyLibSym("PySys_SetArgv", &PySys_SetArgv));
121   PetscCall(PetscDLPyLibSym("PyObject_CallMethod", &PyObject_CallMethod));
122   PetscCall(PetscDLPyLibSym("PyImport_ImportModule", &PyImport_ImportModule));
123   PetscCall(PetscDLPyLibSym("Py_IncRef", &Py_IncRef));
124   PetscCall(PetscDLPyLibSym("Py_DecRef", &Py_DecRef));
125   PetscCall(PetscDLPyLibSym("PyErr_Clear", &PyErr_Clear));
126   PetscCall(PetscDLPyLibSym("PyErr_Occurred", &PyErr_Occurred));
127   PetscCall(PetscDLPyLibSym("PyErr_Fetch", &PyErr_Fetch));
128   PetscCall(PetscDLPyLibSym("PyErr_NormalizeException", &PyErr_NormalizeException));
129   PetscCall(PetscDLPyLibSym("PyErr_Display", &PyErr_Display));
130   PetscCall(PetscDLPyLibSym("PyErr_Restore", &PyErr_Restore));
131   /* XXX TODO: check that ALL symbols were there !!! */
132   PetscCheck(Py_None, PETSC_COMM_SELF, PETSC_ERR_LIB, "Python: failed to load symbols from Python dynamic library %s", pythonlib);
133   PetscCheck(Py_GetVersion, PETSC_COMM_SELF, PETSC_ERR_LIB, "Python: failed to load symbols from Python dynamic library %s", pythonlib);
134   PetscCheck(Py_IsInitialized, PETSC_COMM_SELF, PETSC_ERR_LIB, "Python: failed to load symbols from Python dynamic library %s", pythonlib);
135   PetscCheck(Py_InitializeEx, PETSC_COMM_SELF, PETSC_ERR_LIB, "Python: failed to load symbols from Python dynamic library %s", pythonlib);
136   PetscCheck(Py_Finalize, PETSC_COMM_SELF, PETSC_ERR_LIB, "Python: failed to load symbols from Python dynamic library %s", pythonlib);
137   PetscCall(PetscInfo(NULL, "Python: all required symbols loaded from Python dynamic library %s\n", pythonlib));
138   PetscFunctionReturn(PETSC_SUCCESS);
139 }
140 
141 static char      PetscPythonExe[PETSC_MAX_PATH_LEN] = {0};
142 static char      PetscPythonLib[PETSC_MAX_PATH_LEN] = {0};
143 static PetscBool PetscBeganPython                   = PETSC_FALSE;
144 
145 /*@C
146   PetscPythonFinalize - Finalize PETSc for use with Python.
147 
148   Level: intermediate
149 
150 .seealso: `PetscPythonInitialize()`, `PetscPythonPrintError()`
151 @*/
152 PetscErrorCode PetscPythonFinalize(void)
153 {
154   PetscFunctionBegin;
155   if (PetscBeganPython) {
156     if (Py_IsInitialized()) Py_Finalize();
157   }
158   PetscBeganPython = PETSC_FALSE;
159   PetscFunctionReturn(PETSC_SUCCESS);
160 }
161 
162 /*@C
163   PetscPythonInitialize - Initialize Python for use with PETSc and import petsc4py.
164 
165    Input Parameters:
166 +  pyexe - path to the Python interpreter executable, or `NULL`.
167 -  pylib - full path to the Python dynamic library, or `NULL`.
168 
169   Level: intermediate
170 
171 .seealso: `PetscPythonFinalize()`, `PetscPythonPrintError()`
172 @*/
173 PetscErrorCode PetscPythonInitialize(const char pyexe[], const char pylib[])
174 {
175   PyObject *module = NULL;
176 
177   PetscFunctionBegin;
178   if (PetscBeganPython) PetscFunctionReturn(PETSC_SUCCESS);
179   /* Python executable */
180   if (pyexe && pyexe[0] != 0) {
181     PetscCall(PetscStrncpy(PetscPythonExe, pyexe, sizeof(PetscPythonExe)));
182   } else {
183     PetscCall(PetscPythonFindExecutable(PetscPythonExe, sizeof(PetscPythonExe)));
184   }
185   /* Python dynamic library */
186   if (pylib && pylib[0] != 0) {
187     PetscCall(PetscStrncpy(PetscPythonLib, pylib, sizeof(PetscPythonLib)));
188   } else {
189     PetscCall(PetscPythonFindLibrary(PetscPythonExe, PetscPythonLib, sizeof(PetscPythonLib)));
190   }
191   /* dynamically load Python library */
192   PetscCall(PetscPythonLoadLibrary(PetscPythonLib));
193   /* initialize Python */
194   PetscBeganPython = PETSC_FALSE;
195   if (!Py_IsInitialized()) {
196     static PetscBool registered = PETSC_FALSE;
197     const char      *py_version;
198     PyObject        *sys_path;
199     char             path[PETSC_MAX_PATH_LEN] = {0};
200 
201     /* initialize Python. Py_InitializeEx() prints an error and EXITS the program if it is not successful! */
202     PetscCall(PetscInfo(NULL, "Calling Py_InitializeEx(0)\n"));
203     PetscStackCallExternalVoid("Py_InitializeEx", Py_InitializeEx(0)); /* 0: do not install signal handlers */
204     PetscCall(PetscInfo(NULL, "Py_InitializeEx(0) called successfully\n"));
205 
206     /* build 'sys.argv' list */
207     py_version = Py_GetVersion();
208     if (py_version[0] == '2') {
209       int   argc    = 0;
210       char *argv[1] = {NULL};
211       PySys_SetArgv(argc, argv);
212     }
213     if (py_version[0] == '3') {
214       int      argc    = 0;
215       wchar_t *argv[1] = {NULL};
216       PySys_SetArgv(argc, argv);
217     }
218     /* add PETSC_LIB_DIR in front of 'sys.path' */
219     sys_path = PySys_GetObject("path");
220     if (sys_path) {
221       PetscCall(PetscStrreplace(PETSC_COMM_SELF, "${PETSC_LIB_DIR}", path, sizeof(path)));
222       Py_DecRef(PyObject_CallMethod(sys_path, "insert", "is", (int)0, (char *)path));
223 #if defined(PETSC_PETSC4PY_INSTALL_PATH)
224       {
225         char *rpath;
226         PetscCall(PetscStrallocpy(PETSC_PETSC4PY_INSTALL_PATH, &rpath));
227         Py_DecRef(PyObject_CallMethod(sys_path, "insert", "is", (int)0, rpath));
228         PetscCall(PetscFree(rpath));
229       }
230 #endif
231     }
232     /* register finalizer */
233     if (!registered) {
234       PetscCall(PetscRegisterFinalize(PetscPythonFinalize));
235       registered = PETSC_TRUE;
236     }
237     PetscBeganPython = PETSC_TRUE;
238     PetscCall(PetscInfo(NULL, "Python initialize completed\n"));
239   }
240   /* import 'petsc4py.PETSc' module */
241   PetscCall(PetscFPTrapPush(PETSC_FP_TRAP_OFF));
242   PetscStackCallExternalVoid("PyImport_ImportModule", module = PyImport_ImportModule("petsc4py.PETSc"));
243   PetscCall(PetscFPTrapPop());
244   if (module) {
245     PetscCall(PetscInfo(NULL, "Python: successfully imported module 'petsc4py.PETSc'\n"));
246     Py_DecRef(module);
247     module = NULL;
248   } else {
249     PetscCall(PetscInfo(NULL, "Python: error when importing module 'petsc4py.PETSc'\n"));
250     PetscCall(PetscPythonPrintError());
251     SETERRQ(PETSC_COMM_SELF, PETSC_ERR_PLIB, "Python: could not import module 'petsc4py.PETSc', perhaps your PYTHONPATH does not contain it");
252   }
253   PetscFunctionReturn(PETSC_SUCCESS);
254 }
255 
256 /*@C
257   PetscPythonPrintError - Print any current Python errors.
258 
259   Level: developer
260 
261 .seealso: `PetscPythonInitialize()`, `PetscPythonFinalize()`
262 @*/
263 PetscErrorCode PetscPythonPrintError(void)
264 {
265   PyObject *exc = NULL, *val = NULL, *tb = NULL;
266 
267   PetscFunctionBegin;
268   if (!PetscBeganPython) PetscFunctionReturn(PETSC_SUCCESS);
269   if (!PyErr_Occurred()) PetscFunctionReturn(PETSC_SUCCESS);
270   PyErr_Fetch(&exc, &val, &tb);
271   PyErr_NormalizeException(&exc, &val, &tb);
272   PyErr_Display(exc ? exc : Py_None, val ? val : Py_None, tb ? tb : Py_None);
273   PyErr_Restore(exc, val, tb);
274   PetscFunctionReturn(PETSC_SUCCESS);
275 }
276 
277 PETSC_EXTERN PetscErrorCode (*PetscPythonMonitorSet_C)(PetscObject, const char[]);
278 PetscErrorCode (*PetscPythonMonitorSet_C)(PetscObject, const char[]) = NULL;
279 
280 /*@C
281   PetscPythonMonitorSet - Set a Python monitor for a `PetscObject`
282 
283   Level: developer
284 
285 .seealso: `PetscPythonInitialize()`, `PetscPythonFinalize()`, `PetscPythonPrintError()`
286 @*/
287 PetscErrorCode PetscPythonMonitorSet(PetscObject obj, const char url[])
288 {
289   PetscFunctionBegin;
290   PetscValidHeader(obj, 1);
291   PetscAssertPointer(url, 2);
292   if (!PetscPythonMonitorSet_C) {
293     PetscCall(PetscPythonInitialize(NULL, NULL));
294     PetscCheck(PetscPythonMonitorSet_C, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Couldn't initialize Python support for monitors");
295   }
296   PetscCall(PetscPythonMonitorSet_C(obj, url));
297   PetscFunctionReturn(PETSC_SUCCESS);
298 }
299