Actual source code: pythonsys.c
1: #include <petsc/private/petscimpl.h>
3: #if !defined(PETSC_PYTHON_EXE)
4: #define PETSC_PYTHON_EXE "python"
5: #endif
7: static PetscErrorCode PetscPythonFindExecutable(char pythonexe[], size_t len)
8: {
9: PetscBool flag;
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: }
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;
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, (int)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: }
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
59: PetscBool found = PETSC_FALSE;
61: PetscFunctionBegin;
62: #if defined(PETSC_PYTHON_LIB)
63: PetscCall(PetscStrncpy(pythonlib, PETSC_PYTHON_LIB, pl));
64: PetscFunctionReturn(PETSC_SUCCESS);
65: #endif
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: }
76: typedef struct _Py_object_t PyObject; /* fake definition */
78: static PyObject *Py_None = NULL;
80: static const char *(*Py_GetVersion)(void);
82: static int (*Py_IsInitialized)(void);
83: static void (*Py_InitializeEx)(int);
84: static void (*Py_Finalize)(void);
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 *);
91: static void (*Py_IncRef)(PyObject *);
92: static void (*Py_DecRef)(PyObject *);
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 *);
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)
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: }
141: static char PetscPythonExe[PETSC_MAX_PATH_LEN] = {0};
142: static char PetscPythonLib[PETSC_MAX_PATH_LEN] = {0};
143: static PetscBool PetscBeganPython = PETSC_FALSE;
145: /*@
146: PetscPythonFinalize - Finalize PETSc for use with Python.
148: Level: intermediate
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: }
162: /*@
163: PetscPythonInitialize - Initialize Python for use with PETSc and import petsc4py.
165: Input Parameters:
166: + pyexe - path to the Python interpreter executable, or `NULL`.
167: - pylib - full path to the Python dynamic library, or `NULL`.
169: Level: intermediate
171: .seealso: `PetscPythonFinalize()`, `PetscPythonPrintError()`
172: @*/
173: PetscErrorCode PetscPythonInitialize(const char pyexe[], const char pylib[])
174: {
175: PyObject *module = NULL;
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};
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"));
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: int zero = 0;
222: PetscCall(PetscStrreplace(PETSC_COMM_SELF, "${PETSC_LIB_DIR}", path, sizeof(path)));
223: Py_DecRef(PyObject_CallMethod(sys_path, "insert", "is", zero, (char *)path));
224: #if defined(PETSC_PETSC4PY_INSTALL_PATH)
225: {
226: char *rpath;
227: PetscCall(PetscStrallocpy(PETSC_PETSC4PY_INSTALL_PATH, &rpath));
228: Py_DecRef(PyObject_CallMethod(sys_path, "insert", "is", zero, rpath));
229: PetscCall(PetscFree(rpath));
230: }
231: #endif
232: }
233: /* register finalizer */
234: if (!registered) {
235: PetscCall(PetscRegisterFinalize(PetscPythonFinalize));
236: registered = PETSC_TRUE;
237: }
238: PetscBeganPython = PETSC_TRUE;
239: PetscCall(PetscInfo(NULL, "Python initialize completed\n"));
240: }
241: /* import 'petsc4py.PETSc' module */
242: PetscCall(PetscFPTrapPush(PETSC_FP_TRAP_OFF));
243: PetscStackCallExternalVoid("PyImport_ImportModule", module = PyImport_ImportModule("petsc4py.PETSc"));
244: PetscCall(PetscFPTrapPop());
245: if (module) {
246: PetscCall(PetscInfo(NULL, "Python: successfully imported module 'petsc4py.PETSc'\n"));
247: Py_DecRef(module);
248: module = NULL;
249: } else {
250: PetscCall(PetscInfo(NULL, "Python: error when importing module 'petsc4py.PETSc'\n"));
251: PetscCall(PetscPythonPrintError());
252: SETERRQ(PETSC_COMM_SELF, PETSC_ERR_PLIB, "Python: could not import module 'petsc4py.PETSc', perhaps your PYTHONPATH does not contain it");
253: }
254: PetscFunctionReturn(PETSC_SUCCESS);
255: }
257: /*@C
258: PetscPythonPrintError - Print any current Python errors.
260: Level: developer
262: .seealso: `PetscPythonInitialize()`, `PetscPythonFinalize()`
263: @*/
264: PetscErrorCode PetscPythonPrintError(void)
265: {
266: PyObject *exc = NULL, *val = NULL, *tb = NULL;
268: PetscFunctionBegin;
269: if (!PetscBeganPython) PetscFunctionReturn(PETSC_SUCCESS);
270: if (!PyErr_Occurred()) PetscFunctionReturn(PETSC_SUCCESS);
271: PyErr_Fetch(&exc, &val, &tb);
272: PyErr_NormalizeException(&exc, &val, &tb);
273: PyErr_Display(exc ? exc : Py_None, val ? val : Py_None, tb ? tb : Py_None);
274: PyErr_Restore(exc, val, tb);
275: PetscFunctionReturn(PETSC_SUCCESS);
276: }
278: PETSC_EXTERN PetscErrorCode (*PetscPythonMonitorSet_C)(PetscObject, const char[]);
279: PetscErrorCode (*PetscPythonMonitorSet_C)(PetscObject, const char[]) = NULL;
281: /*@
282: PetscPythonMonitorSet - Set a Python monitor for a `PetscObject`
284: Level: developer
286: .seealso: `PetscPythonInitialize()`, `PetscPythonFinalize()`, `PetscPythonPrintError()`
287: @*/
288: PetscErrorCode PetscPythonMonitorSet(PetscObject obj, const char url[])
289: {
290: PetscFunctionBegin;
292: PetscAssertPointer(url, 2);
293: if (!PetscPythonMonitorSet_C) {
294: PetscCall(PetscPythonInitialize(NULL, NULL));
295: PetscCheck(PetscPythonMonitorSet_C, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Couldn't initialize Python support for monitors");
296: }
297: PetscCall(PetscPythonMonitorSet_C(obj, url));
298: PetscFunctionReturn(PETSC_SUCCESS);
299: }