xref: /petsc/src/sys/python/pythonsys.c (revision d382aafbaf988181ac6819ef14789c4ab78c7a0e)
1 #define PETSC_DLL
2 
3 #include "petscsys.h"       /*I "petscsys.h" I*/
4 
5 /* ---------------------------------------------------------------- */
6 
7 #if !defined(PETSC_PYTHON_EXE)
8 #define PETSC_PYTHON_EXE "python"
9 #endif
10 
11 #undef __FUNCT__
12 #define __FUNCT__ "PetscPythonFindExecutable"
13 static PetscErrorCode PetscPythonFindExecutable(char pythonexe[PETSC_MAX_PATH_LEN])
14 {
15   PetscTruth     flag;
16   PetscErrorCode ierr;
17   PetscFunctionBegin;
18   /* get the path for the Python interpreter executable */
19   ierr = PetscStrncpy(pythonexe,PETSC_PYTHON_EXE,PETSC_MAX_PATH_LEN);CHKERRQ(ierr);
20   ierr = PetscOptionsGetString(PETSC_NULL,"-python",pythonexe,PETSC_MAX_PATH_LEN,&flag);CHKERRQ(ierr);
21   if (!flag || pythonexe[0]==0) {
22     ierr = PetscStrncpy(pythonexe,PETSC_PYTHON_EXE,PETSC_MAX_PATH_LEN);CHKERRQ(ierr);
23   }
24   PetscFunctionReturn(0);
25 }
26 
27 #undef __FUNCT__
28 #define __FUNCT__ "PetscPythonFindLibrary"
29 static PetscErrorCode PetscPythonFindLibrary(char pythonexe[PETSC_MAX_PATH_LEN],
30 					     char pythonlib[PETSC_MAX_PATH_LEN])
31 {
32   const char cmdline[] = "-c 'import sys; print(sys.exec_prefix); print(sys.version[:3])'";
33   char command[PETSC_MAX_PATH_LEN+1+sizeof(cmdline)+1];
34   char prefix[PETSC_MAX_PATH_LEN],version[8],sep[2]={PETSC_DIR_SEPARATOR, 0},*eol;
35   FILE* fp = NULL;
36   char path[PETSC_MAX_PATH_LEN+1];
37   PetscTruth found = PETSC_FALSE;
38   PetscErrorCode ierr;
39   PetscFunctionBegin;
40 
41 #if defined(PETSC_PYTHON_LIB)
42   ierr = PetscStrcpy(pythonlib,PETSC_PYTHON_LIB);CHKERRQ(ierr);
43   PetscFunctionReturn(0);
44 #endif
45 
46   /* call Python to find out the name of the Python dynamic library */
47   ierr = PetscStrncpy(command,pythonexe,PETSC_MAX_PATH_LEN);CHKERRQ(ierr);
48   ierr = PetscStrcat(command," ");CHKERRQ(ierr);
49   ierr = PetscStrcat(command,cmdline);CHKERRQ(ierr);
50 #if defined(PETSC_HAVE_POPEN)
51   ierr = PetscPOpen(PETSC_COMM_SELF,PETSC_NULL,command,"r",&fp);CHKERRQ(ierr);
52   if (!fgets(prefix,sizeof(prefix),fp))
53     { SETERRQ1(PETSC_ERR_PLIB,"Python: bad output from executable: %s",pythonexe); }
54   if (!fgets(version,sizeof(version),fp))
55     { SETERRQ1(PETSC_ERR_PLIB,"Python: bad output from executable: %s",pythonexe); }
56   ierr = PetscPClose(PETSC_COMM_SELF,fp);CHKERRQ(ierr);
57 #else
58   SETERRQ(1,"Python: Aborted due to missing popen()");
59 #endif
60   /* remove newlines */
61   ierr = PetscStrchr(prefix,'\n',&eol);CHKERRQ(ierr);
62   if (eol) eol[0] = 0;
63   ierr = PetscStrchr(version,'\n',&eol);CHKERRQ(ierr);
64   if (eol) eol[0] = 0;
65 
66   /* test for $prefix/lib64/libpythonX.X[.so]*/
67   ierr = PetscStrcpy(pythonlib,prefix);CHKERRQ(ierr);
68   ierr = PetscStrcat(pythonlib,sep);CHKERRQ(ierr);
69   ierr = PetscStrcat(pythonlib,"lib64");CHKERRQ(ierr);
70   ierr = PetscTestDirectory(pythonlib,'r',&found);CHKERRQ(ierr);
71   if (found) {
72     ierr = PetscStrcat(pythonlib,sep);CHKERRQ(ierr);
73     ierr = PetscStrcat(pythonlib,"libpython");CHKERRQ(ierr);
74     ierr = PetscStrcat(pythonlib,version);CHKERRQ(ierr);
75     ierr = PetscDLLibraryRetrieve(PETSC_COMM_SELF,pythonlib,path,PETSC_MAX_PATH_LEN,&found);CHKERRQ(ierr);
76     if (found) PetscFunctionReturn(0);
77   }
78 
79   /* test for $prefix/lib/libpythonX.X[.so]*/
80   ierr = PetscStrcpy(pythonlib,prefix);CHKERRQ(ierr);
81   ierr = PetscStrcat(pythonlib,sep);CHKERRQ(ierr);
82   ierr = PetscStrcat(pythonlib,"lib");CHKERRQ(ierr);
83   ierr = PetscTestDirectory(pythonlib,'r',&found);CHKERRQ(ierr);
84   if (found) {
85     ierr = PetscStrcat(pythonlib,sep);CHKERRQ(ierr);
86     ierr = PetscStrcat(pythonlib,"libpython");CHKERRQ(ierr);
87     ierr = PetscStrcat(pythonlib,version);CHKERRQ(ierr);
88     ierr = PetscDLLibraryRetrieve(PETSC_COMM_SELF,pythonlib,path,PETSC_MAX_PATH_LEN,&found);CHKERRQ(ierr);
89     if (found) PetscFunctionReturn(0);
90   }
91 
92   /* nothing good found */
93   ierr = PetscMemzero(pythonlib,PETSC_MAX_PATH_LEN);CHKERRQ(ierr);
94   ierr = PetscInfo(0,"Python dynamic library not found\n");CHKERRQ(ierr);
95 
96   PetscFunctionReturn(0);
97 }
98 
99 /* ---------------------------------------------------------------- */
100 
101 typedef struct _Py_object_t PyObject; /* fake definition */
102 
103 static int   	 (*Py_IsInitialized)(void);
104 static void  	 (*Py_InitializeEx)(int);
105 static void  	 (*Py_Finalize)(void);
106 
107 static void      (*PySys_SetArgv)(int, char **);
108 static PyObject* (*PyImport_ImportModule)(const char *);
109 
110 static void      (*Py_IncRef)(PyObject *);
111 static void      (*Py_DecRef)(PyObject *);
112 
113 static void      (*PyErr_Clear)(void);
114 static PyObject* (*PyErr_Occurred)(void);
115 
116 
117 #define PetscDLPyLibOpen(libname) \
118   PetscDLLibraryAppend(PETSC_COMM_SELF,&DLLibrariesLoaded,libname)
119 #define PetscDLPyLibSym(symbol, value) \
120   PetscDLLibrarySym(PETSC_COMM_SELF,&DLLibrariesLoaded,PETSC_NULL,symbol,(void**)value)
121 #define PetscDLPyLibClose(comm) \
122   do { } while(0)
123 
124 #undef __FUNCT__
125 #define __FUNCT__ "PetscPythonLoadLibrary"
126 static PetscErrorCode PetscPythonLoadLibrary(const char pythonlib[])
127 {
128   PetscErrorCode ierr;
129   PetscFunctionBegin;
130 
131   /* open the Python dynamic library */
132   ierr = PetscDLPyLibOpen(pythonlib);CHKERRQ(ierr);
133   ierr = PetscInfo1(0,"Python: loaded dynamic library %s\n", pythonlib);CHKERRQ(ierr);
134   /* look required symbols from the Python C-API */
135   ierr = PetscDLPyLibSym("Py_IsInitialized"      , &Py_IsInitialized      );CHKERRQ(ierr);
136   ierr = PetscDLPyLibSym("Py_InitializeEx"       , &Py_InitializeEx       );CHKERRQ(ierr);
137   ierr = PetscDLPyLibSym("Py_Finalize"           , &Py_Finalize           );CHKERRQ(ierr);
138   ierr = PetscDLPyLibSym("PySys_SetArgv"         , &PySys_SetArgv         );CHKERRQ(ierr);
139   ierr = PetscDLPyLibSym("PyImport_ImportModule" , &PyImport_ImportModule );CHKERRQ(ierr);
140   ierr = PetscDLPyLibSym("Py_IncRef"             , &Py_IncRef             );CHKERRQ(ierr);
141   ierr = PetscDLPyLibSym("Py_DecRef"             , &Py_DecRef             );CHKERRQ(ierr);
142   ierr = PetscDLPyLibSym("PyErr_Clear"           , &PyErr_Clear           );CHKERRQ(ierr);
143   ierr = PetscDLPyLibSym("PyErr_Occurred"        , &PyErr_Occurred        );CHKERRQ(ierr);
144   /* XXX TODO: check that ALL symbols were there !!! */
145   if (!Py_IsInitialized) {SETERRQ(1,"Python: failed to load symbols from dynamic library");}
146   if (!Py_InitializeEx)  {SETERRQ(1,"Python: failed to load symbols from dynamic library");}
147   if (!Py_Finalize)      {SETERRQ(1,"Python: failed to load symbols from dynamic library");}
148   ierr = PetscInfo(0,"Python: all required symbols loaded from Python dynamic library\n");CHKERRQ(ierr);
149 
150   PetscFunctionReturn(0);
151 }
152 
153 /* ---------------------------------------------------------------- */
154 
155 static char       PetscPythonExe[PETSC_MAX_PATH_LEN] = { 0 };
156 static char       PetscPythonLib[PETSC_MAX_PATH_LEN] = { 0 };
157 static PetscTruth PetscBeganPython = PETSC_FALSE;
158 
159 #undef __FUNCT__
160 #define __FUNCT__ "PetscPythonFinalize"
161 /*@C
162   PetscPythonFinalize - Finalize Python.
163 
164   Level: intermediate
165 
166 .keywords: Python
167 @*/
168 PetscErrorCode PETSC_DLLEXPORT PetscPythonFinalize(void)
169 {
170   PetscFunctionBegin;
171   if (PetscBeganPython) { if (Py_IsInitialized()) Py_Finalize(); }
172   PetscBeganPython = PETSC_FALSE;
173   PetscFunctionReturn(0);
174 }
175 
176 #undef __FUNCT__
177 #define __FUNCT__ "PetscPythonInitialize"
178 /*@C
179   PetscPythonInitialize - Initialize Python and import petsc4py.
180 
181    Input Parameter:
182 +  pyexe - path to the Python interpreter executable, or PETSC_NULL.
183 -  pylib - full path to the Python dynamic library, or PETSC_NULL.
184 
185   Level: intermediate
186 
187 .keywords: Python
188 
189 @*/
190 PetscErrorCode PETSC_DLLEXPORT PetscPythonInitialize(const char pyexe[],const char pylib[])
191 {
192   int               argc       = 0;
193   char              **argv     = 0;
194   PyObject          *module    = 0;
195   static PetscTruth registered = PETSC_FALSE;
196   PetscErrorCode    ierr;
197   PetscFunctionBegin;
198   if (PetscBeganPython) PetscFunctionReturn(0);
199   /* Python executable */
200   if (pyexe && pyexe[0] != 0) {
201     ierr = PetscStrncpy(PetscPythonExe,pyexe,sizeof(PetscPythonExe));CHKERRQ(ierr);
202   } else {
203     ierr = PetscPythonFindExecutable(PetscPythonExe);CHKERRQ(ierr);
204   }
205   /* Python dynamic library */
206   if (pylib && pylib[0] != 0) {
207     ierr = PetscStrncpy(PetscPythonLib,pylib,sizeof(PetscPythonLib));CHKERRQ(ierr);
208   } else {
209     ierr = PetscPythonFindLibrary(PetscPythonExe,PetscPythonLib);CHKERRQ(ierr);
210   }
211   /* dynamically load Python library */
212   ierr = PetscPythonLoadLibrary(PetscPythonLib);CHKERRQ(ierr);
213   /* initialize Python */
214   PetscBeganPython = PETSC_FALSE;
215   if (!Py_IsInitialized()) {
216     /* call below does not install signal handlers */
217     Py_InitializeEx(0);
218     /* call below required to build 'sys.argv' list */
219     ierr = PetscGetArgs(&argc,&argv);CHKERRQ(ierr);
220     if (argc && argv && argv[0]) PySys_SetArgv(argc,argv);
221     /* register finalizer */
222     if (!registered) {
223       ierr = PetscRegisterFinalize(PetscPythonFinalize);CHKERRQ(ierr);
224       registered = PETSC_TRUE;
225     }
226     PetscBeganPython = PETSC_TRUE;
227   }
228   /* import 'petsc4py.PETSc' module */
229   module = PyImport_ImportModule("petsc4py.PETSc");
230   if (module) {
231     ierr = PetscInfo(0,"Python: successfully imported  module 'petsc4py.PETSc'\n");CHKERRQ(ierr);
232     Py_DecRef(module); module = 0;
233   } else {
234     SETERRQ(PETSC_ERR_PLIB,"Python: could not import module 'petsc4py.PETSc', perhaps your PYTHONPATH does not contain it\n");
235   }
236   PetscFunctionReturn(0);
237 }
238 
239 /* ---------------------------------------------------------------- */
240