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, pl, fp), PETSC_COMM_SELF, PETSC_ERR_PLIB, "Python: bad output from executable: %s\nRunning: %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:   const char cmdline1[] = "-c 'import os, sysconfig; print(os.path.join(sysconfig.get_config_var(\"LIBDIR\"),sysconfig.get_config_var(\"LDLIBRARY\")))'";
 50:   const char cmdline2[] = "-c 'import os, sysconfig; print(os.path.join(sysconfig.get_path(\"stdlib\"),os.path.pardir,\"libpython\"+sysconfig.get_python_version()+\".dylib\"))'";
 51:   const char cmdline3[] = "-c 'import os, sysconfig; print(os.path.join(sysconfig.get_config_var(\"LIBPL\"),sysconfig.get_config_var(\"LDLIBRARY\")))'";
 52:   const char cmdline4[] = "-c 'import sysconfig; print(sysconfig.get_config_var(\"LIBPYTHON\"))'";
 53:   const char cmdline5[] = "-c 'import os, sysconfig; import sys;print(os.path.join(sysconfig.get_config_var(\"LIBDIR\"),\"libpython\"+sys.version[:3]+\".so\"))'";

 55:   PetscBool found = PETSC_FALSE;

 57:   PetscFunctionBegin;
 58: #if defined(PETSC_PYTHON_LIB)
 59:   PetscCall(PetscStrncpy(pythonlib, PETSC_PYTHON_LIB, pl));
 60:   PetscFunctionReturn(PETSC_SUCCESS);
 61: #endif

 63:   PetscCall(PetscPythonFindLibraryName(pythonexe, cmdline1, pythonlib, pl, &found));
 64:   if (!found) PetscCall(PetscPythonFindLibraryName(pythonexe, cmdline2, pythonlib, pl, &found));
 65:   if (!found) PetscCall(PetscPythonFindLibraryName(pythonexe, cmdline3, pythonlib, pl, &found));
 66:   if (!found) PetscCall(PetscPythonFindLibraryName(pythonexe, cmdline4, pythonlib, pl, &found));
 67:   if (!found) PetscCall(PetscPythonFindLibraryName(pythonexe, cmdline5, pythonlib, pl, &found));
 68:   PetscCall(PetscInfo(NULL, "Python library  %s found %d\n", pythonlib, found));
 69:   PetscFunctionReturn(PETSC_SUCCESS);
 70: }

 72: typedef struct _Py_object_t PyObject; /* fake definition */

 74: static PyObject *Py_None = NULL;

 76: static const char *(*Py_GetVersion)(void);

 78: static int (*Py_IsInitialized)(void);
 79: static void (*Py_InitializeEx)(int);
 80: static void (*Py_Finalize)(void);

 82: static void (*PySys_SetArgv)(int, void *);
 83: static PyObject *(*PySys_GetObject)(const char *);
 84: static PyObject *(*PyObject_CallMethod)(PyObject *, const char *, const char *, ...);
 85: static PyObject *(*PyImport_ImportModule)(const char *);

 87: static void (*Py_IncRef)(PyObject *);
 88: static void (*Py_DecRef)(PyObject *);

 90: static void (*PyErr_Clear)(void);
 91: static PyObject *(*PyErr_Occurred)(void);
 92: static void (*PyErr_Fetch)(PyObject **, PyObject **, PyObject **);
 93: static void (*PyErr_NormalizeException)(PyObject **, PyObject **, PyObject **);
 94: static void (*PyErr_Display)(PyObject *, PyObject *, PyObject *);
 95: static void (*PyErr_Restore)(PyObject *, PyObject *, PyObject *);

 97: #define PetscDLPyLibOpen(libname)      PetscDLLibraryAppend(PETSC_COMM_SELF, &PetscDLLibrariesLoaded, libname)
 98: #define PetscDLPyLibSym(symbol, value) PetscDLLibrarySym(PETSC_COMM_SELF, &PetscDLLibrariesLoaded, NULL, symbol, (void **)value)
 99: #define PetscDLPyLibClose(comm) \
100:   do { \
101:   } while (0)

103: static PetscErrorCode PetscPythonLoadLibrary(const char pythonlib[])
104: {
105:   PetscFunctionBegin;
106:   /* open the Python dynamic library */
107:   PetscCall(PetscDLPyLibOpen(pythonlib));
108:   PetscCall(PetscInfo(NULL, "Python: loaded dynamic library %s\n", pythonlib));
109:   /* look required symbols from the Python C-API */
110:   PetscCall(PetscDLPyLibSym("_Py_NoneStruct", &Py_None));
111:   PetscCall(PetscDLPyLibSym("Py_GetVersion", &Py_GetVersion));
112:   PetscCall(PetscDLPyLibSym("Py_IsInitialized", &Py_IsInitialized));
113:   PetscCall(PetscDLPyLibSym("Py_InitializeEx", &Py_InitializeEx));
114:   PetscCall(PetscDLPyLibSym("Py_Finalize", &Py_Finalize));
115:   PetscCall(PetscDLPyLibSym("PySys_GetObject", &PySys_GetObject));
116:   PetscCall(PetscDLPyLibSym("PySys_SetArgv", &PySys_SetArgv));
117:   PetscCall(PetscDLPyLibSym("PyObject_CallMethod", &PyObject_CallMethod));
118:   PetscCall(PetscDLPyLibSym("PyImport_ImportModule", &PyImport_ImportModule));
119:   PetscCall(PetscDLPyLibSym("Py_IncRef", &Py_IncRef));
120:   PetscCall(PetscDLPyLibSym("Py_DecRef", &Py_DecRef));
121:   PetscCall(PetscDLPyLibSym("PyErr_Clear", &PyErr_Clear));
122:   PetscCall(PetscDLPyLibSym("PyErr_Occurred", &PyErr_Occurred));
123:   PetscCall(PetscDLPyLibSym("PyErr_Fetch", &PyErr_Fetch));
124:   PetscCall(PetscDLPyLibSym("PyErr_NormalizeException", &PyErr_NormalizeException));
125:   PetscCall(PetscDLPyLibSym("PyErr_Display", &PyErr_Display));
126:   PetscCall(PetscDLPyLibSym("PyErr_Restore", &PyErr_Restore));
127:   /* XXX TODO: check that ALL symbols were there !!! */
128:   PetscCheck(Py_None, PETSC_COMM_SELF, PETSC_ERR_LIB, "Python: failed to load symbols from Python dynamic library %s", pythonlib);
129:   PetscCheck(Py_GetVersion, PETSC_COMM_SELF, PETSC_ERR_LIB, "Python: failed to load symbols from Python dynamic library %s", pythonlib);
130:   PetscCheck(Py_IsInitialized, PETSC_COMM_SELF, PETSC_ERR_LIB, "Python: failed to load symbols from Python dynamic library %s", pythonlib);
131:   PetscCheck(Py_InitializeEx, PETSC_COMM_SELF, PETSC_ERR_LIB, "Python: failed to load symbols from Python dynamic library %s", pythonlib);
132:   PetscCheck(Py_Finalize, PETSC_COMM_SELF, PETSC_ERR_LIB, "Python: failed to load symbols from Python dynamic library %s", pythonlib);
133:   PetscCall(PetscInfo(NULL, "Python: all required symbols loaded from Python dynamic library %s\n", pythonlib));
134:   PetscFunctionReturn(PETSC_SUCCESS);
135: }

137: static char      PetscPythonExe[PETSC_MAX_PATH_LEN] = {0};
138: static char      PetscPythonLib[PETSC_MAX_PATH_LEN] = {0};
139: static PetscBool PetscBeganPython                   = PETSC_FALSE;

141: /*@C
142:   PetscPythonFinalize - Finalize PETSc for use with Python.

144:   Level: intermediate

146: .seealso: `PetscPythonInitialize()`, `PetscPythonPrintError()`
147: @*/
148: PetscErrorCode PetscPythonFinalize(void)
149: {
150:   PetscFunctionBegin;
151:   if (PetscBeganPython) {
152:     if (Py_IsInitialized()) Py_Finalize();
153:   }
154:   PetscBeganPython = PETSC_FALSE;
155:   PetscFunctionReturn(PETSC_SUCCESS);
156: }

158: /*@C
159:   PetscPythonInitialize - Initialize Python for use with PETSc and import petsc4py.

161:    Input Parameters:
162: +  pyexe - path to the Python interpreter executable, or `NULL`.
163: -  pylib - full path to the Python dynamic library, or `NULL`.

165:   Level: intermediate

167: .seealso: `PetscPythonFinalize()`, `PetscPythonPrintError()`
168: @*/
169: PetscErrorCode PetscPythonInitialize(const char pyexe[], const char pylib[])
170: {
171:   PyObject *module = NULL;

173:   PetscFunctionBegin;
174:   if (PetscBeganPython) PetscFunctionReturn(PETSC_SUCCESS);
175:   /* Python executable */
176:   if (pyexe && pyexe[0] != 0) {
177:     PetscCall(PetscStrncpy(PetscPythonExe, pyexe, sizeof(PetscPythonExe)));
178:   } else {
179:     PetscCall(PetscPythonFindExecutable(PetscPythonExe, sizeof(PetscPythonExe)));
180:   }
181:   /* Python dynamic library */
182:   if (pylib && pylib[0] != 0) {
183:     PetscCall(PetscStrncpy(PetscPythonLib, pylib, sizeof(PetscPythonLib)));
184:   } else {
185:     PetscCall(PetscPythonFindLibrary(PetscPythonExe, PetscPythonLib, sizeof(PetscPythonLib)));
186:   }
187:   /* dynamically load Python library */
188:   PetscCall(PetscPythonLoadLibrary(PetscPythonLib));
189:   /* initialize Python */
190:   PetscBeganPython = PETSC_FALSE;
191:   if (!Py_IsInitialized()) {
192:     static PetscBool registered = PETSC_FALSE;
193:     const char      *py_version;
194:     PyObject        *sys_path;
195:     char             path[PETSC_MAX_PATH_LEN] = {0};

197:     /* initialize Python. Py_InitializeEx() prints an error and EXITS the program if it is not successful! */
198:     PetscCall(PetscInfo(NULL, "Calling Py_InitializeEx(0);\n"));
199:     Py_InitializeEx(0); /* 0: do not install signal handlers */
200:     PetscCall(PetscInfo(NULL, "Py_InitializeEx(0) called successfully;\n"));

202:     /*  build 'sys.argv' list */
203:     py_version = Py_GetVersion();
204:     if (py_version[0] == '2') {
205:       int   argc    = 0;
206:       char *argv[1] = {NULL};
207:       PySys_SetArgv(argc, argv);
208:     }
209:     if (py_version[0] == '3') {
210:       int      argc    = 0;
211:       wchar_t *argv[1] = {NULL};
212:       PySys_SetArgv(argc, argv);
213:     }
214:     /* add PETSC_LIB_DIR in front of 'sys.path' */
215:     sys_path = PySys_GetObject("path");
216:     if (sys_path) {
217:       PetscCall(PetscStrreplace(PETSC_COMM_SELF, "${PETSC_LIB_DIR}", path, sizeof(path)));
218:       Py_DecRef(PyObject_CallMethod(sys_path, "insert", "is", (int)0, (char *)path));
219: #if defined(PETSC_PETSC4PY_INSTALL_PATH)
220:       {
221:         char *rpath;
222:         PetscCall(PetscStrallocpy(PETSC_PETSC4PY_INSTALL_PATH, &rpath));
223:         Py_DecRef(PyObject_CallMethod(sys_path, "insert", "is", (int)0, rpath));
224:         PetscCall(PetscFree(rpath));
225:       }
226: #endif
227:     }
228:     /* register finalizer */
229:     if (!registered) {
230:       PetscCall(PetscRegisterFinalize(PetscPythonFinalize));
231:       registered = PETSC_TRUE;
232:     }
233:     PetscBeganPython = PETSC_TRUE;
234:     PetscCall(PetscInfo(NULL, "Python initialize completed.\n"));
235:   }
236:   /* import 'petsc4py.PETSc' module */
237:   module = PyImport_ImportModule("petsc4py.PETSc");
238:   if (module) {
239:     PetscCall(PetscInfo(NULL, "Python: successfully imported  module 'petsc4py.PETSc'\n"));
240:     Py_DecRef(module);
241:     module = NULL;
242:   } else {
243:     PetscCall(PetscPythonPrintError());
244:     SETERRQ(PETSC_COMM_SELF, PETSC_ERR_PLIB, "Python: could not import module 'petsc4py.PETSc', perhaps your PYTHONPATH does not contain it");
245:   }
246:   PetscFunctionReturn(PETSC_SUCCESS);
247: }

249: /*@C
250:   PetscPythonPrintError - Print any current Python errors.

252:   Level: developer

254: .seealso: `PetscPythonInitialize()`, `PetscPythonFinalize()`
255: @*/
256: PetscErrorCode PetscPythonPrintError(void)
257: {
258:   PyObject *exc = NULL, *val = NULL, *tb = NULL;

260:   PetscFunctionBegin;
261:   if (!PetscBeganPython) PetscFunctionReturn(PETSC_SUCCESS);
262:   if (!PyErr_Occurred()) PetscFunctionReturn(PETSC_SUCCESS);
263:   PyErr_Fetch(&exc, &val, &tb);
264:   PyErr_NormalizeException(&exc, &val, &tb);
265:   PyErr_Display(exc ? exc : Py_None, val ? val : Py_None, tb ? tb : Py_None);
266:   PyErr_Restore(exc, val, tb);
267:   PetscFunctionReturn(PETSC_SUCCESS);
268: }

270: PETSC_EXTERN PetscErrorCode (*PetscPythonMonitorSet_C)(PetscObject, const char[]);
271: PetscErrorCode (*PetscPythonMonitorSet_C)(PetscObject, const char[]) = NULL;

273: /*@C
274:   PetscPythonMonitorSet - Set a Python monitor for a `PetscObject`

276:   Level: developer

278: .seealso: `PetscPythonInitialize()`, `PetscPythonFinalize()`, `PetscPythonPrintError()`
279: @*/
280: PetscErrorCode PetscPythonMonitorSet(PetscObject obj, const char url[])
281: {
282:   PetscFunctionBegin;
284:   PetscAssertPointer(url, 2);
285:   if (!PetscPythonMonitorSet_C) {
286:     PetscCall(PetscPythonInitialize(NULL, NULL));
287:     PetscCheck(PetscPythonMonitorSet_C, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Couldn't initialize Python support for monitors");
288:   }
289:   PetscCall(PetscPythonMonitorSet_C(obj, url));
290:   PetscFunctionReturn(PETSC_SUCCESS);
291: }