Actual source code: pythonsys.c
petsc-3.7.1 2016-05-15
Report Typos and Errors

      1: #include <petsc/private/petscimpl.h>       /*I "petscsys.h" I*/

      3: /* ---------------------------------------------------------------- */

      5: #if !defined(PETSC_PYTHON_EXE)
      6: #define PETSC_PYTHON_EXE "python"
      7: #endif

     11: static PetscErrorCode PetscPythonFindExecutable(char pythonexe[PETSC_MAX_PATH_LEN])
     12: {
     13:   PetscBool      flag;

     17:   /* get the path for the Python interpreter executable */
     18:   PetscStrncpy(pythonexe,PETSC_PYTHON_EXE,PETSC_MAX_PATH_LEN);
     19:   PetscOptionsGetString(NULL,NULL,"-python",pythonexe,PETSC_MAX_PATH_LEN,&flag);
     20:   if (!flag || pythonexe[0]==0) {
     21:     PetscStrncpy(pythonexe,PETSC_PYTHON_EXE,PETSC_MAX_PATH_LEN);
     22:   }
     23:   return(0);
     24: }

     28: static PetscErrorCode PetscPythonFindLibrary(char pythonexe[PETSC_MAX_PATH_LEN],char pythonlib[PETSC_MAX_PATH_LEN])
     29: {
     30:   const char     cmdline[] = "-c 'import sys; print(sys.exec_prefix); print(sys.version[:3])'";
     31:   char           command[PETSC_MAX_PATH_LEN+1+sizeof(cmdline)+1];
     32:   char           prefix[PETSC_MAX_PATH_LEN],version[8],sep[2]={PETSC_DIR_SEPARATOR, 0},*eol;
     33:   FILE           *fp = NULL;
     34:   char           path[PETSC_MAX_PATH_LEN+1];
     35:   PetscBool      found = PETSC_FALSE;

     39: #if defined(PETSC_PYTHON_LIB)
     40:   PetscStrcpy(pythonlib,PETSC_PYTHON_LIB);
     41:   return(0);
     42: #endif

     44:   /* call Python to find out the name of the Python dynamic library */
     45:   PetscStrncpy(command,pythonexe,PETSC_MAX_PATH_LEN);
     46:   PetscStrcat(command," ");
     47:   PetscStrcat(command,cmdline);
     48: #if defined(PETSC_HAVE_POPEN)
     49:   PetscPOpen(PETSC_COMM_SELF,NULL,command,"r",&fp);
     50:   if (!fgets(prefix,sizeof(prefix),fp)) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_PLIB,"Python: bad output from executable: %s",pythonexe);
     51:   if (!fgets(version,sizeof(version),fp)) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_PLIB,"Python: bad output from executable: %s",pythonexe);
     52:   PetscPClose(PETSC_COMM_SELF,fp,NULL);
     53: #else
     54:   SETERRQ(PETSC_COMM_SELF,1,"Python: Aborted due to missing popen()");
     55: #endif
     56:   /* remove newlines */
     57:   PetscStrchr(prefix,'\n',&eol);
     58:   if (eol) eol[0] = 0;
     59:   PetscStrchr(version,'\n',&eol);
     60:   if (eol) eol[0] = 0;

     62:   /* test for $prefix/lib64/libpythonX.X[.so]*/
     63:   PetscStrcpy(pythonlib,prefix);
     64:   PetscStrcat(pythonlib,sep);
     65:   PetscStrcat(pythonlib,"lib64");
     66:   PetscTestDirectory(pythonlib,'r',&found);
     67:   if (found) {
     68:     PetscStrcat(pythonlib,sep);
     69:     PetscStrcat(pythonlib,"libpython");
     70:     PetscStrcat(pythonlib,version);
     71:     PetscDLLibraryRetrieve(PETSC_COMM_SELF,pythonlib,path,PETSC_MAX_PATH_LEN,&found);
     72:     if (found) return(0);
     73:   }

     75:   /* test for $prefix/lib/libpythonX.X[.so]*/
     76:   PetscStrcpy(pythonlib,prefix);
     77:   PetscStrcat(pythonlib,sep);
     78:   PetscStrcat(pythonlib,"lib");
     79:   PetscTestDirectory(pythonlib,'r',&found);
     80:   if (found) {
     81:     PetscStrcat(pythonlib,sep);
     82:     PetscStrcat(pythonlib,"libpython");
     83:     PetscStrcat(pythonlib,version);
     84:     PetscDLLibraryRetrieve(PETSC_COMM_SELF,pythonlib,path,PETSC_MAX_PATH_LEN,&found);
     85:     if (found) return(0);
     86:   }

     88:   /* nothing good found */
     89:   PetscMemzero(pythonlib,PETSC_MAX_PATH_LEN);
     90:   PetscInfo(0,"Python dynamic library not found\n");
     91:   return(0);
     92: }

     94: /* ---------------------------------------------------------------- */

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

     98: static PyObject* Py_None = 0;

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

    102: static int       (*Py_IsInitialized)(void);
    103: static void      (*Py_InitializeEx)(int);
    104: static void      (*Py_Finalize)(void);

    106: static void      (*PySys_SetArgv)(int,char**);
    107: static PyObject* (*PySys_GetObject)(const char*);
    108: static PyObject* (*PyObject_CallMethod)(PyObject*,const char*, const char*, ...);
    109: static PyObject* (*PyImport_ImportModule)(const char*);

    111: static void      (*Py_IncRef)(PyObject*);
    112: static void      (*Py_DecRef)(PyObject*);

    114: static void      (*PyErr_Clear)(void);
    115: static PyObject* (*PyErr_Occurred)(void);
    116: static void      (*PyErr_Fetch)(PyObject**,PyObject**,PyObject**);
    117: static void      (*PyErr_NormalizeException)(PyObject**,PyObject**, PyObject**);
    118: static void      (*PyErr_Display)(PyObject*,PyObject*,PyObject*);
    119: static void      (*PyErr_Restore)(PyObject*,PyObject*,PyObject*);

    122: #define PetscDLPyLibOpen(libname) \
    123:   PetscDLLibraryAppend(PETSC_COMM_SELF,&PetscDLLibrariesLoaded,libname)
    124: #define PetscDLPyLibSym(symbol, value) \
    125:   PetscDLLibrarySym(PETSC_COMM_SELF,&PetscDLLibrariesLoaded,NULL,symbol,(void**)value)
    126: #define PetscDLPyLibClose(comm) \
    127:   do { } while (0)

    131: static PetscErrorCode PetscPythonLoadLibrary(const char pythonlib[])
    132: {

    136:   /* open the Python dynamic library */
    137:   PetscDLPyLibOpen(pythonlib);
    138:   PetscInfo1(0,"Python: loaded dynamic library %s\n", pythonlib);
    139:   /* look required symbols from the Python C-API */
    140:   PetscDLPyLibSym("_Py_NoneStruct"        , &Py_None               );
    141:   PetscDLPyLibSym("Py_GetVersion"         , &Py_GetVersion         );
    142:   PetscDLPyLibSym("Py_IsInitialized"      , &Py_IsInitialized      );
    143:   PetscDLPyLibSym("Py_InitializeEx"       , &Py_InitializeEx       );
    144:   PetscDLPyLibSym("Py_Finalize"           , &Py_Finalize           );
    145:   PetscDLPyLibSym("PySys_GetObject"       , &PySys_GetObject       );
    146:   PetscDLPyLibSym("PySys_SetArgv"         , &PySys_SetArgv         );
    147:   PetscDLPyLibSym("PyObject_CallMethod"   , &PyObject_CallMethod   );
    148:   PetscDLPyLibSym("PyImport_ImportModule" , &PyImport_ImportModule );
    149:   PetscDLPyLibSym("Py_IncRef"             , &Py_IncRef             );
    150:   PetscDLPyLibSym("Py_DecRef"             , &Py_DecRef             );
    151:   PetscDLPyLibSym("PyErr_Clear"           , &PyErr_Clear           );
    152:   PetscDLPyLibSym("PyErr_Occurred"        , &PyErr_Occurred        );
    153:   PetscDLPyLibSym("PyErr_Fetch"             , &PyErr_Fetch             );
    154:   PetscDLPyLibSym("PyErr_NormalizeException", &PyErr_NormalizeException);
    155:   PetscDLPyLibSym("PyErr_Display",            &PyErr_Display           );
    156:   PetscDLPyLibSym("PyErr_Restore",            &PyErr_Restore           );
    157:   /* XXX TODO: check that ALL symbols were there !!! */
    158:   if (!Py_None)          SETERRQ(PETSC_COMM_SELF,1,"Python: failed to load symbols from dynamic library");
    159:   if (!Py_GetVersion)    SETERRQ(PETSC_COMM_SELF,1,"Python: failed to load symbols from dynamic library");
    160:   if (!Py_IsInitialized) SETERRQ(PETSC_COMM_SELF,1,"Python: failed to load symbols from dynamic library");
    161:   if (!Py_InitializeEx)  SETERRQ(PETSC_COMM_SELF,1,"Python: failed to load symbols from dynamic library");
    162:   if (!Py_Finalize)      SETERRQ(PETSC_COMM_SELF,1,"Python: failed to load symbols from dynamic library");
    163:   PetscInfo(0,"Python: all required symbols loaded from Python dynamic library\n");
    164:   return(0);
    165: }

    167: /* ---------------------------------------------------------------- */

    169: static char      PetscPythonExe[PETSC_MAX_PATH_LEN] = { 0 };
    170: static char      PetscPythonLib[PETSC_MAX_PATH_LEN] = { 0 };
    171: static PetscBool PetscBeganPython = PETSC_FALSE;

    175: /*@C
    176:   PetscPythonFinalize - Finalize Python.

    178:   Level: intermediate

    180: .keywords: Python
    181: @*/
    182: PetscErrorCode  PetscPythonFinalize(void)
    183: {
    185:   if (PetscBeganPython) { if (Py_IsInitialized()) Py_Finalize(); }
    186:   PetscBeganPython = PETSC_FALSE;
    187:   return(0);
    188: }

    192: /*@C
    193:   PetscPythonInitialize - Initialize Python and import petsc4py.

    195:    Input Parameter:
    196: +  pyexe - path to the Python interpreter executable, or NULL.
    197: -  pylib - full path to the Python dynamic library, or NULL.

    199:   Level: intermediate

    201: .keywords: Python

    203: @*/
    204: PetscErrorCode  PetscPythonInitialize(const char pyexe[],const char pylib[])
    205: {
    206:   PyObject       *module = 0;

    210:   if (PetscBeganPython) return(0);
    211:   /* Python executable */
    212:   if (pyexe && pyexe[0] != 0) {
    213:     PetscStrncpy(PetscPythonExe,pyexe,sizeof(PetscPythonExe));
    214:   } else {
    215:     PetscPythonFindExecutable(PetscPythonExe);
    216:   }
    217:   /* Python dynamic library */
    218:   if (pylib && pylib[0] != 0) {
    219:     PetscStrncpy(PetscPythonLib,pylib,sizeof(PetscPythonLib));
    220:   } else {
    221:     PetscPythonFindLibrary(PetscPythonExe,PetscPythonLib);
    222:   }
    223:   /* dynamically load Python library */
    224:   PetscPythonLoadLibrary(PetscPythonLib);
    225:   /* initialize Python */
    226:   PetscBeganPython = PETSC_FALSE;
    227:   if (!Py_IsInitialized()) {
    228:     static PetscBool registered = PETSC_FALSE;
    229:     const char       *py_version;
    230:     PyObject         *sys_path;
    231:     char             path[PETSC_MAX_PATH_LEN] = { 0 };

    233:     /* initialize Python */
    234:     Py_InitializeEx(0); /* 0: do not install signal handlers */
    235:     /*  build 'sys.argv' list */
    236:     py_version = Py_GetVersion();
    237:     if (py_version[0] == '2') {
    238:       int argc = 0; char **argv = 0;
    239:       PetscGetArgs(&argc,&argv);
    240:       PySys_SetArgv(argc,argv);
    241:     }
    242:     if (py_version[0] == '3') {
    243:       /* XXX 'argv' is type 'wchar_t**' */
    244:       PySys_SetArgv(0,NULL);
    245:     }
    246:     /* add PETSC_LIB_DIR in front of 'sys.path' */
    247:     sys_path = PySys_GetObject("path");
    248:     if (sys_path) {
    249:       PetscStrreplace(PETSC_COMM_SELF,"${PETSC_LIB_DIR}",path,sizeof(path));
    250:       Py_DecRef(PyObject_CallMethod(sys_path,"insert","is",(int)0,(char*)path));
    251:     }
    252:     /* register finalizer */
    253:     if (!registered) {
    254:       PetscRegisterFinalize(PetscPythonFinalize);

    256:       registered = PETSC_TRUE;
    257:     }
    258:     PetscBeganPython = PETSC_TRUE;
    259:   }
    260:   /* import 'petsc4py.PETSc' module */
    261:   module = PyImport_ImportModule("petsc4py.PETSc");
    262:   if (module) {
    263:     PetscInfo(0,"Python: successfully imported  module 'petsc4py.PETSc'\n");

    265:     Py_DecRef(module); module = 0;
    266:   } else {
    267:     PetscPythonPrintError();
    268:     SETERRQ(PETSC_COMM_SELF,PETSC_ERR_PLIB,"Python: could not import module 'petsc4py.PETSc', perhaps your PYTHONPATH does not contain it\n");
    269:   }
    270:   return(0);
    271: }

    275: /*@C
    276:   PetscPythonPrintError - Print Python errors.

    278:   Level: developer

    280: .keywords: Python

    282: @*/
    283: PetscErrorCode  PetscPythonPrintError(void)
    284: {
    285:   PyObject *exc=0, *val=0, *tb=0;

    288:   if (!PetscBeganPython) return(0);
    289:   if (!PyErr_Occurred()) return(0);
    290:   PyErr_Fetch(&exc,&val,&tb);
    291:   PyErr_NormalizeException(&exc,&val,&tb);
    292:   PyErr_Display(exc ? exc : Py_None,
    293:                 val ? val : Py_None,
    294:                 tb  ? tb  : Py_None);
    295:   PyErr_Restore(exc,val,tb);
    296:   return(0);
    297: }

    299: /* ---------------------------------------------------------------- */

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

    306: /*@C
    307:   PetscPythonMonitorSet - Set Python monitor

    309:   Level: developer

    311: .keywords: Python

    313: @*/
    314: PetscErrorCode PetscPythonMonitorSet(PetscObject obj, const char url[])
    315: {

    321:   if (!PetscPythonMonitorSet_C) {
    322:     PetscPythonInitialize(NULL,NULL);
    323:     if (!PetscPythonMonitorSet_C) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_LIB,"Couldn't initialize Python support for monitors");
    324:   }
    325:   PetscPythonMonitorSet_C(obj,url);
    326:   return(0);
    327: }

    329: /* ---------------------------------------------------------------- */