Actual source code: pythonsys.c
petsc-3.8.3 2017-12-09
1: #include <petsc/private/petscimpl.h>
3: /* ---------------------------------------------------------------- */
5: #if !defined(PETSC_PYTHON_EXE)
6: #define PETSC_PYTHON_EXE "python"
7: #endif
9: static PetscErrorCode PetscPythonFindExecutable(char pythonexe[PETSC_MAX_PATH_LEN])
10: {
11: PetscBool flag;
15: /* get the path for the Python interpreter executable */
16: PetscStrncpy(pythonexe,PETSC_PYTHON_EXE,PETSC_MAX_PATH_LEN);
17: PetscOptionsGetString(NULL,NULL,"-python",pythonexe,PETSC_MAX_PATH_LEN,&flag);
18: if (!flag || pythonexe[0]==0) {
19: PetscStrncpy(pythonexe,PETSC_PYTHON_EXE,PETSC_MAX_PATH_LEN);
20: }
21: return(0);
22: }
24: static PetscErrorCode PetscPythonFindLibrary(char pythonexe[PETSC_MAX_PATH_LEN],char pythonlib[PETSC_MAX_PATH_LEN])
25: {
26: const char cmdline[] = "-c 'import sys; print(sys.exec_prefix); print(sys.version[:3])'";
27: char command[PETSC_MAX_PATH_LEN+1+sizeof(cmdline)+1];
28: char prefix[PETSC_MAX_PATH_LEN],version[8],sep[2]={PETSC_DIR_SEPARATOR, 0},*eol;
29: FILE *fp = NULL;
30: char path[PETSC_MAX_PATH_LEN+1];
31: PetscBool found = PETSC_FALSE;
35: #if defined(PETSC_PYTHON_LIB)
36: PetscStrcpy(pythonlib,PETSC_PYTHON_LIB);
37: return(0);
38: #endif
40: /* call Python to find out the name of the Python dynamic library */
41: PetscStrncpy(command,pythonexe,PETSC_MAX_PATH_LEN);
42: PetscStrcat(command," ");
43: PetscStrcat(command,cmdline);
44: #if defined(PETSC_HAVE_POPEN)
45: PetscPOpen(PETSC_COMM_SELF,NULL,command,"r",&fp);
46: if (!fgets(prefix,sizeof(prefix),fp)) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_PLIB,"Python: bad output from executable: %s",pythonexe);
47: if (!fgets(version,sizeof(version),fp)) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_PLIB,"Python: bad output from executable: %s",pythonexe);
48: PetscPClose(PETSC_COMM_SELF,fp,NULL);
49: #else
50: SETERRQ(PETSC_COMM_SELF,1,"Python: Aborted due to missing popen()");
51: #endif
52: /* remove newlines */
53: PetscStrchr(prefix,'\n',&eol);
54: if (eol) eol[0] = 0;
55: PetscStrchr(version,'\n',&eol);
56: if (eol) eol[0] = 0;
58: /* test for $prefix/lib64/libpythonX.X[.so]*/
59: PetscStrcpy(pythonlib,prefix);
60: PetscStrcat(pythonlib,sep);
61: PetscStrcat(pythonlib,"lib64");
62: PetscTestDirectory(pythonlib,'r',&found);
63: if (found) {
64: PetscStrcat(pythonlib,sep);
65: PetscStrcat(pythonlib,"libpython");
66: PetscStrcat(pythonlib,version);
67: PetscDLLibraryRetrieve(PETSC_COMM_SELF,pythonlib,path,PETSC_MAX_PATH_LEN,&found);
68: if (found) return(0);
69: }
71: /* test for $prefix/lib/libpythonX.X[.so]*/
72: PetscStrcpy(pythonlib,prefix);
73: PetscStrcat(pythonlib,sep);
74: PetscStrcat(pythonlib,"lib");
75: PetscTestDirectory(pythonlib,'r',&found);
76: if (found) {
77: PetscStrcat(pythonlib,sep);
78: PetscStrcat(pythonlib,"libpython");
79: PetscStrcat(pythonlib,version);
80: PetscDLLibraryRetrieve(PETSC_COMM_SELF,pythonlib,path,PETSC_MAX_PATH_LEN,&found);
81: if (found) return(0);
82: }
84: /* nothing good found */
85: PetscMemzero(pythonlib,PETSC_MAX_PATH_LEN);
86: PetscInfo(0,"Python dynamic library not found\n");
87: return(0);
88: }
90: /* ---------------------------------------------------------------- */
92: typedef struct _Py_object_t PyObject; /* fake definition */
94: static PyObject* Py_None = 0;
96: static const char* (*Py_GetVersion)(void);
98: static int (*Py_IsInitialized)(void);
99: static void (*Py_InitializeEx)(int);
100: static void (*Py_Finalize)(void);
102: static void (*PySys_SetArgv)(int,char**);
103: static PyObject* (*PySys_GetObject)(const char*);
104: static PyObject* (*PyObject_CallMethod)(PyObject*,const char*, const char*, ...);
105: static PyObject* (*PyImport_ImportModule)(const char*);
107: static void (*Py_IncRef)(PyObject*);
108: static void (*Py_DecRef)(PyObject*);
110: static void (*PyErr_Clear)(void);
111: static PyObject* (*PyErr_Occurred)(void);
112: static void (*PyErr_Fetch)(PyObject**,PyObject**,PyObject**);
113: static void (*PyErr_NormalizeException)(PyObject**,PyObject**, PyObject**);
114: static void (*PyErr_Display)(PyObject*,PyObject*,PyObject*);
115: static void (*PyErr_Restore)(PyObject*,PyObject*,PyObject*);
118: #define PetscDLPyLibOpen(libname) \
119: PetscDLLibraryAppend(PETSC_COMM_SELF,&PetscDLLibrariesLoaded,libname)
120: #define PetscDLPyLibSym(symbol, value) \
121: PetscDLLibrarySym(PETSC_COMM_SELF,&PetscDLLibrariesLoaded,NULL,symbol,(void**)value)
122: #define PetscDLPyLibClose(comm) \
123: do { } while (0)
125: static PetscErrorCode PetscPythonLoadLibrary(const char pythonlib[])
126: {
130: /* open the Python dynamic library */
131: PetscDLPyLibOpen(pythonlib);
132: PetscInfo1(0,"Python: loaded dynamic library %s\n", pythonlib);
133: /* look required symbols from the Python C-API */
134: PetscDLPyLibSym("_Py_NoneStruct" , &Py_None );
135: PetscDLPyLibSym("Py_GetVersion" , &Py_GetVersion );
136: PetscDLPyLibSym("Py_IsInitialized" , &Py_IsInitialized );
137: PetscDLPyLibSym("Py_InitializeEx" , &Py_InitializeEx );
138: PetscDLPyLibSym("Py_Finalize" , &Py_Finalize );
139: PetscDLPyLibSym("PySys_GetObject" , &PySys_GetObject );
140: PetscDLPyLibSym("PySys_SetArgv" , &PySys_SetArgv );
141: PetscDLPyLibSym("PyObject_CallMethod" , &PyObject_CallMethod );
142: PetscDLPyLibSym("PyImport_ImportModule" , &PyImport_ImportModule );
143: PetscDLPyLibSym("Py_IncRef" , &Py_IncRef );
144: PetscDLPyLibSym("Py_DecRef" , &Py_DecRef );
145: PetscDLPyLibSym("PyErr_Clear" , &PyErr_Clear );
146: PetscDLPyLibSym("PyErr_Occurred" , &PyErr_Occurred );
147: PetscDLPyLibSym("PyErr_Fetch" , &PyErr_Fetch );
148: PetscDLPyLibSym("PyErr_NormalizeException", &PyErr_NormalizeException);
149: PetscDLPyLibSym("PyErr_Display", &PyErr_Display );
150: PetscDLPyLibSym("PyErr_Restore", &PyErr_Restore );
151: /* XXX TODO: check that ALL symbols were there !!! */
152: if (!Py_None) SETERRQ(PETSC_COMM_SELF,1,"Python: failed to load symbols from dynamic library");
153: if (!Py_GetVersion) SETERRQ(PETSC_COMM_SELF,1,"Python: failed to load symbols from dynamic library");
154: if (!Py_IsInitialized) SETERRQ(PETSC_COMM_SELF,1,"Python: failed to load symbols from dynamic library");
155: if (!Py_InitializeEx) SETERRQ(PETSC_COMM_SELF,1,"Python: failed to load symbols from dynamic library");
156: if (!Py_Finalize) SETERRQ(PETSC_COMM_SELF,1,"Python: failed to load symbols from dynamic library");
157: PetscInfo(0,"Python: all required symbols loaded from Python dynamic library\n");
158: return(0);
159: }
161: /* ---------------------------------------------------------------- */
163: static char PetscPythonExe[PETSC_MAX_PATH_LEN] = { 0 };
164: static char PetscPythonLib[PETSC_MAX_PATH_LEN] = { 0 };
165: static PetscBool PetscBeganPython = PETSC_FALSE;
167: /*@C
168: PetscPythonFinalize - Finalize Python.
170: Level: intermediate
172: .keywords: Python
173: @*/
174: PetscErrorCode PetscPythonFinalize(void)
175: {
177: if (PetscBeganPython) { if (Py_IsInitialized()) Py_Finalize(); }
178: PetscBeganPython = PETSC_FALSE;
179: return(0);
180: }
182: /*@C
183: PetscPythonInitialize - Initialize Python and import petsc4py.
185: Input Parameter:
186: + pyexe - path to the Python interpreter executable, or NULL.
187: - pylib - full path to the Python dynamic library, or NULL.
189: Level: intermediate
191: .keywords: Python
193: @*/
194: PetscErrorCode PetscPythonInitialize(const char pyexe[],const char pylib[])
195: {
196: PyObject *module = 0;
200: if (PetscBeganPython) return(0);
201: /* Python executable */
202: if (pyexe && pyexe[0] != 0) {
203: PetscStrncpy(PetscPythonExe,pyexe,sizeof(PetscPythonExe));
204: } else {
205: PetscPythonFindExecutable(PetscPythonExe);
206: }
207: /* Python dynamic library */
208: if (pylib && pylib[0] != 0) {
209: PetscStrncpy(PetscPythonLib,pylib,sizeof(PetscPythonLib));
210: } else {
211: PetscPythonFindLibrary(PetscPythonExe,PetscPythonLib);
212: }
213: /* dynamically load Python library */
214: PetscPythonLoadLibrary(PetscPythonLib);
215: /* initialize Python */
216: PetscBeganPython = PETSC_FALSE;
217: if (!Py_IsInitialized()) {
218: static PetscBool registered = PETSC_FALSE;
219: const char *py_version;
220: PyObject *sys_path;
221: char path[PETSC_MAX_PATH_LEN] = { 0 };
223: /* initialize Python */
224: Py_InitializeEx(0); /* 0: do not install signal handlers */
225: /* build 'sys.argv' list */
226: py_version = Py_GetVersion();
227: if (py_version[0] == '2') {
228: int argc = 0; char **argv = 0;
229: PetscGetArgs(&argc,&argv);
230: PySys_SetArgv(argc,argv);
231: }
232: if (py_version[0] == '3') {
233: /* XXX 'argv' is type 'wchar_t**' */
234: PySys_SetArgv(0,NULL);
235: }
236: /* add PETSC_LIB_DIR in front of 'sys.path' */
237: sys_path = PySys_GetObject("path");
238: if (sys_path) {
239: PetscStrreplace(PETSC_COMM_SELF,"${PETSC_LIB_DIR}",path,sizeof(path));
240: Py_DecRef(PyObject_CallMethod(sys_path,"insert","is",(int)0,(char*)path));
241: }
242: /* register finalizer */
243: if (!registered) {
244: PetscRegisterFinalize(PetscPythonFinalize);
246: registered = PETSC_TRUE;
247: }
248: PetscBeganPython = PETSC_TRUE;
249: }
250: /* import 'petsc4py.PETSc' module */
251: module = PyImport_ImportModule("petsc4py.PETSc");
252: if (module) {
253: PetscInfo(0,"Python: successfully imported module 'petsc4py.PETSc'\n");
255: Py_DecRef(module); module = 0;
256: } else {
257: PetscPythonPrintError();
258: SETERRQ(PETSC_COMM_SELF,PETSC_ERR_PLIB,"Python: could not import module 'petsc4py.PETSc', perhaps your PYTHONPATH does not contain it\n");
259: }
260: return(0);
261: }
263: /*@C
264: PetscPythonPrintError - Print Python errors.
266: Level: developer
268: .keywords: Python
270: @*/
271: PetscErrorCode PetscPythonPrintError(void)
272: {
273: PyObject *exc=0, *val=0, *tb=0;
276: if (!PetscBeganPython) return(0);
277: if (!PyErr_Occurred()) return(0);
278: PyErr_Fetch(&exc,&val,&tb);
279: PyErr_NormalizeException(&exc,&val,&tb);
280: PyErr_Display(exc ? exc : Py_None,
281: val ? val : Py_None,
282: tb ? tb : Py_None);
283: PyErr_Restore(exc,val,tb);
284: return(0);
285: }
287: /* ---------------------------------------------------------------- */
289: PETSC_EXTERN PetscErrorCode (*PetscPythonMonitorSet_C)(PetscObject,const char[]);
290: PetscErrorCode (*PetscPythonMonitorSet_C)(PetscObject,const char[]) = NULL;
292: /*@C
293: PetscPythonMonitorSet - Set Python monitor
295: Level: developer
297: .keywords: Python
299: @*/
300: PetscErrorCode PetscPythonMonitorSet(PetscObject obj, const char url[])
301: {
307: if (!PetscPythonMonitorSet_C) {
308: PetscPythonInitialize(NULL,NULL);
309: if (!PetscPythonMonitorSet_C) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_LIB,"Couldn't initialize Python support for monitors");
310: }
311: PetscPythonMonitorSet_C(obj,url);
312: return(0);
313: }
315: /* ---------------------------------------------------------------- */