Ejemplo n.º 1
0
	void AddResource(const DKString& name, DKResource* res) override
	{
		if (name.Length() > 0 && res)
		{
			if (this->object && Py_IsInitialized())
			{
				DCObjectCallPyCallableGIL([&]()
				{
					PyObject* obj = DCResourceFromObject(res);
					if (obj)
					{
						PyObject* ret = PyObject_CallMethod(object,
							"addResource", "NO",
							PyUnicode_FromWideChar(name, -1),
							obj);
						Py_XDECREF(ret);
					}
					Py_XDECREF(obj);
				});
			}
		}
	}
Ejemplo n.º 2
0
static void real_init(void) {
#ifdef VS_TARGET_OS_WINDOWS

    const wchar_t *keyPython64 = L"SOFTWARE\\Python\\PythonCore\\3.5\\InstallPath";
    const wchar_t *keyPython32 = L"SOFTWARE\\Python\\PythonCore\\3.5-32\\InstallPath";

    DWORD dwType = REG_SZ;
    HKEY hKey = 0;

    wchar_t value[1024];
    DWORD valueLength = 1000;
    if (RegOpenKeyW(HKEY_CURRENT_USER, keyPython64, &hKey) != ERROR_SUCCESS
        && RegOpenKeyW(HKEY_CURRENT_USER, keyPython32, &hKey) != ERROR_SUCCESS
        && RegOpenKeyW(HKEY_LOCAL_MACHINE, keyPython64, &hKey) != ERROR_SUCCESS
        && RegOpenKeyW(HKEY_LOCAL_MACHINE, keyPython32, &hKey) != ERROR_SUCCESS)
        return;
    LSTATUS status = RegQueryValueExW(hKey, L"", nullptr, &dwType, (LPBYTE)&value, &valueLength);
    RegCloseKey(hKey);
    if (status != ERROR_SUCCESS)
        return;

    std::wstring pyPath = value;
    pyPath += L"python35.dll";

    HMODULE pythonDll = LoadLibraryW(pyPath.c_str());
    if (!pythonDll)
        return;
#endif
    int preInitialized = Py_IsInitialized();
    if (!preInitialized)
        Py_InitializeEx(0);
    s = PyGILState_Ensure();
    if (import_vapoursynth())
        return;
    if (vpy_initVSScript())
        return;
    ts = PyEval_SaveThread();
    initialized = true;
}
Ejemplo n.º 3
0
static void ue_PySWidget_dealloc(ue_PySWidget *self)
{
#if defined(UEPY_MEMORY_DEBUG)
	UE_LOG(LogPython, Warning, TEXT("Destroying ue_PySWidget %p mapped to %s %p (slate refcount: %d)"), self, *self->s_widget->GetTypeAsString(), &self->s_widget.Get(), self->s_widget.GetSharedReferenceCount());
#endif

	if (self->weakreflist != nullptr)
		PyObject_ClearWeakRefs((PyObject *)self);

	// decrement widget reference count
	// but only if python vm is still fully active (hack to avoid crashes on editor shutdown)
	if (Py_IsInitialized())
	{
		self->Widget = SNullWidget::NullWidget;
	}
	else
	{
		UE_LOG(LogPython, Warning, TEXT("Python VM is being destroyed, skipping ue_PySWidget destruction"));
	}
	Py_TYPE(self)->tp_free((PyObject *)self);

}
Ejemplo n.º 4
0
int Predictor::process() {
    //1st step: initialize Python
    //load Python modules by calling C API of Python
    Py_Initialize(); //cout << "iniialized" << endl;
    //check initialization
    if (!Py_IsInitialized())
    {
        return -1;
    }

    //2nd step: load sys module
    PyRun_SimpleString("import sys");

    //3rd step: load parameters, for example, ./sample.py arg1 arg2
    //PyRun_SimpleString("sys.argv['arg1','arg2']");

    //4th step: call python script to run the trainning process
    if (!PyRun_SimpleString("execfile('./sample.py')")) return -1;

    // close python interpretor
    Py_Finalize();
    return 0;
}
Ejemplo n.º 5
0
GLdouble double_global_const_attr(const char* attr_str) {
	bool py_needed_init = false;

	if(!Py_IsInitialized() ) {
		Py_Initialize();
		py_needed_init = true;
	}

	PyObject *py_attr = get_py_attr(attr_str);

	if(!py_attr) {
		return NULL;
	}

	GLdouble output = PyFloat_AsDouble(py_attr);
	Py_XDECREF(py_attr);

	if(py_needed_init) {
		Py_Finalize();
	}

	return output;
}
Ejemplo n.º 6
0
char char_global_const_attr(const char* attr_str) {
	bool py_needed_init = false;

	if(!Py_IsInitialized() ) {
		Py_Initialize();
		py_needed_init = true;
	}

	PyObject *py_attr = get_py_attr(attr_str);

	if(!py_attr) {
		return NULL;
	}

	char output = PyString_AsString(py_attr)[0];
	Py_XDECREF(py_attr);

	if(py_needed_init) {
		Py_Finalize();
	}

	return output;
}
Ejemplo n.º 7
0
 lwc::Loader* LWC_CreateLoader(const char*, void*) {
   if (Py_IsInitialized()) {
     WasInitialized = true;
   } else {
     #if !defined(_WIN32) && !defined(__APPLE__)
     // On Ubunty (9.04 at least), without this hack, python binary modules fail to load
     // After a little search on the web, it seems that Ubuntu's python is compiled a weird way
     char ver[32];
     sprintf(ver, "%.1f", PY_VER);
     std::string pyso = "libpython";
     pyso += ver;
     pyso += ".so";
     dlopen((char*) pyso.c_str(), RTLD_LAZY|RTLD_GLOBAL);
     #endif
     WasInitialized = false;
     Py_SetProgramName("lwc_python");
     //PyEval_InitThreads();
     Py_Initialize();
   }
   
   lwc::Loader *l = new PLoader();
   return l;
 }
Ejemplo n.º 8
0
int
weechat_plugin_end (struct t_weechat_plugin *plugin)
{
    /* unload all scripts */
    python_quiet = 1;
    plugin_script_end (plugin, &python_scripts, &weechat_python_unload_all);
    python_quiet = 0;

    /* free python interpreter */
    if (python_mainThreadState != NULL)
    {
        /* PyEval_AcquireLock (); */
        PyThreadState_Swap (python_mainThreadState);
        /* PyEval_ReleaseLock (); */
        python_mainThreadState = NULL;
    }

    Py_Finalize ();
    if (Py_IsInitialized () != 0)
    {
        weechat_printf (NULL,
                        weechat_gettext ("%s%s: unable to free interpreter"),
                        weechat_prefix ("error"), PYTHON_PLUGIN_NAME);
    }

    /* free some data */
    if (python2_bin)
        free (python2_bin);
    if (python_action_install_list)
        free (python_action_install_list);
    if (python_action_remove_list)
        free (python_action_remove_list);
    if (python_action_autoload_list)
        free (python_action_autoload_list);

    return WEECHAT_RC_OK;
}
Ejemplo n.º 9
0
int python_call_fns(char* function,fnsDesc *desc){
	PyObject *pFunc = NULL, *pValue= NULL, *pArg = NULL;
		int ret=0;
		if (!Py_IsInitialized())
			return -1;
		SWIG_init();		// Initialise SWIG types

		if (pModule != NULL) {
			pFunc = PyObject_GetAttrString(pModule, function);
			if (pFunc && PyCallable_Check(pFunc)) {
				pArg = SWIG_NewPointerObj(SWIG_as_voidptr(desc), SWIGTYPE_p_fns_desc, SWIG_POINTER_NEW |  0 );
				if (pArg) {
					pValue = PyObject_CallFunction(pFunc, "O", pArg);
				}
				if (pValue != NULL) {
					ret =  PyInt_AsLong(pValue);
					//printf("Result of call: %d\n",ret);
					Py_DECREF(pValue);
				} else {
					Py_DECREF(pFunc);
					PyErr_Print();
					fprintf(stderr, "Call failed\n");
					return -1;
				}
			} else {
				if (PyErr_Occurred())
					PyErr_Print();
				fprintf(stderr, "Cannot find function \n");
			}
			Py_XDECREF(pFunc);

		} else {
			PyErr_Print();
			fprintf(stderr, "Failed to load \"%s\"\n",function);
		}
		return ret;
}
Ejemplo n.º 10
0
int
Py_SetStandardStreamEncoding(const char *encoding, const char *errors)
{
    if (Py_IsInitialized()) {
        /* This is too late to have any effect */
        return -1;
    }
    /* Can't call PyErr_NoMemory() on errors, as Python hasn't been
     * initialised yet.
     *
     * However, the raw memory allocators are initialised appropriately
     * as C static variables, so _PyMem_RawStrdup is OK even though
     * Py_Initialize hasn't been called yet.
     */
    if (encoding) {
        _Py_StandardStreamEncoding = _PyMem_RawStrdup(encoding);
        if (!_Py_StandardStreamEncoding) {
            return -2;
        }
    }
    if (errors) {
        _Py_StandardStreamErrors = _PyMem_RawStrdup(errors);
        if (!_Py_StandardStreamErrors) {
            if (_Py_StandardStreamEncoding) {
                PyMem_RawFree(_Py_StandardStreamEncoding);
            }
            return -3;
        }
    }
#ifdef MS_WINDOWS
    if (_Py_StandardStreamEncoding) {
        /* Overriding the stream encoding implies legacy streams */
        Py_LegacyWindowsStdioFlag = 1;
    }
#endif
    return 0;
}
Ejemplo n.º 11
0
PyObject *
Py_InitModule4(char *name, PyMethodDef *methods, char *doc,
	       PyObject *passthrough, int module_api_version)
{
	PyObject *m, *d, *v;
	PyMethodDef *ml;
	if (!Py_IsInitialized())
	    Py_FatalError("Interpreter not initialized (version mismatch?)");
	if (module_api_version != PYTHON_API_VERSION)
		fprintf(stderr, api_version_warning,
			name, PYTHON_API_VERSION, name, module_api_version);
	if (_Py_PackageContext != NULL) {
		char *p = strrchr(_Py_PackageContext, '.');
		if (p != NULL && strcmp(name, p+1) == 0) {
			name = _Py_PackageContext;
			_Py_PackageContext = NULL;
		}
	}
	if ((m = PyImport_AddModule(name)) == NULL)
		return NULL;
	d = PyModule_GetDict(m);
	for (ml = methods; ml->ml_name != NULL; ml++) {
		v = PyCFunction_New(ml, passthrough);
		if (v == NULL)
			return NULL;
		if (PyDict_SetItemString(d, ml->ml_name, v) != 0)
			return NULL;
		Py_DECREF(v);
	}
	if (doc != NULL) {
		v = PyString_FromString(doc);
		if (v == NULL || PyDict_SetItemString(d, "__doc__", v) != 0)
			return NULL;
		Py_DECREF(v);
	}
	return m;
}
Ejemplo n.º 12
0
ssize_t uwsgi_python_logger(struct uwsgi_logger *ul, char *message, size_t len) {
	if (!Py_IsInitialized()) return -1;

	UWSGI_GET_GIL

	if (!ul->configured) {
		PyObject *py_logging = PyImport_ImportModule("logging");
		if (!py_logging) goto clear;
		PyObject *py_logging_dict = PyModule_GetDict(py_logging);
		if (!py_logging_dict) goto clear;
		PyObject *py_getLogger = PyDict_GetItemString(py_logging_dict, "getLogger");
		if (!py_getLogger) goto clear;
		PyObject *py_getLogger_args = NULL;
		if (ul->arg) {
			py_getLogger_args = PyTuple_New(1);
			PyTuple_SetItem(py_getLogger_args, 0, PyString_FromString(ul->arg));
		}
                ul->data = (void *) PyEval_CallObject(py_getLogger, py_getLogger_args);
                if (PyErr_Occurred()) {
                	PyErr_Clear();
                }
		Py_XDECREF(py_getLogger_args);
		if (!ul->data) goto clear;
		ul->configured = 1;
	}

	PyObject_CallMethod((PyObject *) ul->data, "error", "(s#)", message, len);
        if (PyErr_Occurred()) {
        	PyErr_Clear();
        }
	UWSGI_RELEASE_GIL
	return len;
clear:

	UWSGI_RELEASE_GIL
	return -1;
}
Ejemplo n.º 13
0
// modena_model_t instantiates the surrogate model
modena_model_t *modena_model_new
(
    const char *modelId
)
{
    // Initialize the Python Interpreter
    if(!Py_IsInitialized())
    {
        Py_Initialize();
    }

    // Initialize this module
    initlibmodena();

    PyObject *args = PyTuple_New(0);
    PyObject *kw = Py_BuildValue("{s:s}", "modelId", modelId);

    PyObject *m = PyObject_Call((PyObject *) &modena_model_tType, args, kw);
    Py_DECREF(args);
    Py_DECREF(kw);
    if(!m){ Modena_PyErr_Print(); }

    return (modena_model_t *) m;
}
Ejemplo n.º 14
0
static gboolean
cedit_python_init (CeditPluginLoaderPython *loader)
{
	PyObject *mdict, *tuple;
	PyObject *cedit, *ceditutils, *ceditcommands, *ceditplugins;
	PyObject *gettext, *install, *gettext_args;
	//char *argv[] = { "cedit", NULL };
	char *argv[] = { CEDIT_PLUGINS_LIBS_DIR, NULL };
#ifdef HAVE_SIGACTION
	gint res;
	struct sigaction old_sigint;
#endif

	if (loader->priv->init_failed)
	{
		/* We already failed to initialized Python, don't need to
		 * retry again */
		return FALSE;
	}
	
	if (Py_IsInitialized ())
	{
		/* Python has already been successfully initialized */
		return TRUE;
	}

	/* We are trying to initialize Python for the first time,
	   set init_failed to FALSE only if the entire initialization process
	   ends with success */
	loader->priv->init_failed = TRUE;

	/* Hack to make python not overwrite SIGINT: this is needed to avoid
	 * the crash reported on bug #326191 */

	/* CHECK: can't we use Py_InitializeEx instead of Py_Initialize in order
          to avoid to manage signal handlers ? - Paolo (Dec. 31, 2006) */

#ifdef HAVE_SIGACTION
	/* Save old handler */
	res = sigaction (SIGINT, NULL, &old_sigint);  
	if (res != 0)
	{
		g_warning ("Error initializing Python interpreter: cannot get "
		           "handler to SIGINT signal (%s)",
		           g_strerror (errno));

		return FALSE;
	}
#endif

	/* Python initialization */
	Py_Initialize ();

#ifdef HAVE_SIGACTION
	/* Restore old handler */
	res = sigaction (SIGINT, &old_sigint, NULL);
	if (res != 0)
	{
		g_warning ("Error initializing Python interpreter: cannot restore "
		           "handler to SIGINT signal (%s).",
		           g_strerror (errno));

		goto python_init_error;
	}
#endif

	PySys_SetArgv (1, argv);

	if (!cedit_check_pygtk2 ())
	{
		/* Warning message already printed in check_pygtk2 */
		goto python_init_error;
	}

	/* import gobject */	
	cedit_init_pygobject ();
	if (PyErr_Occurred ())
	{
		g_warning ("Error initializing Python interpreter: could not import pygobject.");

		goto python_init_error;		
	}

	/* import gtk */
	cedit_init_pygtk ();
	if (PyErr_Occurred ())
	{
		g_warning ("Error initializing Python interpreter: could not import pygtk.");

		goto python_init_error;
	}
	
	/* import gtksourceview */
	cedit_init_pygtksourceview ();
	if (PyErr_Occurred ())
	{
		PyErr_Print ();

		g_warning ("Error initializing Python interpreter: could not import pygtksourceview.");

		goto python_init_error;
	}	
	
	/* import cedit */
	cedit = Py_InitModule ("cedit", pycedit_functions);
	mdict = PyModule_GetDict (cedit);

	pycedit_register_classes (mdict);
	pycedit_add_constants (cedit, "CEDIT_");

	/* cedit version */
	tuple = Py_BuildValue("(iii)", 
			      CEDIT_MAJOR_VERSION,
			      CEDIT_MINOR_VERSION,
			      CEDIT_MICRO_VERSION);
	PyDict_SetItemString(mdict, "version", tuple);
	Py_DECREF(tuple);
	
	/* Retrieve the Python type for cedit.Plugin */
	PyCeditPlugin_Type = (PyTypeObject *) PyDict_GetItemString (mdict, "Plugin"); 
	if (PyCeditPlugin_Type == NULL)
	{
		PyErr_Print ();

		goto python_init_error;
	}

	/* import cedit.utils */
	ceditutils = Py_InitModule ("cedit.utils", pyceditutils_functions);
	PyDict_SetItemString (mdict, "utils", ceditutils);

	/* import cedit.commands */
	ceditcommands = Py_InitModule ("cedit.commands", pyceditcommands_functions);
	PyDict_SetItemString (mdict, "commands", ceditcommands);

	/* initialize empty cedit.plugins module */
	ceditplugins = Py_InitModule ("cedit.plugins", NULL);
	PyDict_SetItemString (mdict, "plugins", ceditplugins);

	mdict = PyModule_GetDict (ceditutils);
	pyceditutils_register_classes (mdict);
	
	mdict = PyModule_GetDict (ceditcommands);
	pyceditcommands_register_classes (mdict);

	/* i18n support */
	gettext = PyImport_ImportModule ("gettext");
	if (gettext == NULL)
	{
		g_warning ("Error initializing Python interpreter: could not import gettext.");

		goto python_init_error;
	}

	mdict = PyModule_GetDict (gettext);
	install = PyDict_GetItemString (mdict, "install");
	gettext_args = Py_BuildValue ("ss", GETTEXT_PACKAGE, CEDIT_LOCALEDIR);
	PyObject_CallObject (install, gettext_args);
	Py_DECREF (gettext_args);
	
	/* Python has been successfully initialized */
	loader->priv->init_failed = FALSE;
	
	return TRUE;
	
python_init_error:

	g_warning ("Please check the installation of all the Python related packages required "
	           "by cedit and try again.");

	PyErr_Clear ();

	cedit_python_shutdown (loader);

	return FALSE;
}
Ejemplo n.º 15
0
int pythonmod_init(struct module_env* env, int id)
{
   /* Initialize module */
   FILE* script_py = NULL;
   PyObject* py_cfg, *res;
   PyGILState_STATE gil;
   struct pythonmod_env* pe = (struct pythonmod_env*)calloc(1, sizeof(struct pythonmod_env));
   if (!pe) 
   {
      log_err("pythonmod: malloc failure");
      return 0;
   }

   env->modinfo[id] = (void*) pe;

   /* Initialize module */
   pe->fname = env->cfg->python_script;
   if(pe->fname==NULL || pe->fname[0]==0) {
      log_err("pythonmod: no script given.");
      return 0;
   }

   /* Initialize Python libraries */
   if (!Py_IsInitialized()) 
   {
#if PY_MAJOR_VERSION >= 3
      wchar_t progname[8];
      mbstowcs(progname, "unbound", 8);
#else
      char *progname = "unbound";
#endif
      Py_SetProgramName(progname);
      Py_NoSiteFlag = 1;
      Py_Initialize();
      PyEval_InitThreads();
      SWIG_init();
      pe->mainthr = PyEval_SaveThread();
   }

   gil = PyGILState_Ensure();

   /* Initialize Python */
   PyRun_SimpleString("import sys \n");
   PyRun_SimpleString("sys.path.append('.') \n");
   if(env->cfg->directory && env->cfg->directory[0]) {
   	char wdir[1524];
   	snprintf(wdir, sizeof(wdir), "sys.path.append('%s') \n",
		env->cfg->directory);
   	PyRun_SimpleString(wdir);
   }
   PyRun_SimpleString("sys.path.append('"RUN_DIR"') \n");
   PyRun_SimpleString("sys.path.append('"SHARE_DIR"') \n");
   PyRun_SimpleString("import distutils.sysconfig \n");
   PyRun_SimpleString("sys.path.append(distutils.sysconfig.get_python_lib(1,0)) \n");
   if (PyRun_SimpleString("from unboundmodule import *\n") < 0)
   {
      log_err("pythonmod: cannot initialize core module: unboundmodule.py"); 
      PyGILState_Release(gil);
      return 0;
   }

   /* Check Python file load */
   if ((script_py = fopen(pe->fname, "r")) == NULL) 
   {
      log_err("pythonmod: can't open file %s for reading", pe->fname);
      PyGILState_Release(gil);
      return 0;
   }

   /* Load file */
   pe->module = PyImport_AddModule("__main__");
   pe->dict = PyModule_GetDict(pe->module);
   pe->data = Py_None;
   Py_INCREF(pe->data);
   PyModule_AddObject(pe->module, "mod_env", pe->data);

   /* TODO: deallocation of pe->... if an error occurs */
  
   if (PyRun_SimpleFile(script_py, pe->fname) < 0) 
   {
      log_err("pythonmod: can't parse Python script %s", pe->fname);
      PyGILState_Release(gil);
      return 0;
   }

   fclose(script_py);

   if ((pe->func_init = PyDict_GetItemString(pe->dict, "init")) == NULL) 
   {
      log_err("pythonmod: function init is missing in %s", pe->fname);
      PyGILState_Release(gil);
      return 0;
   }
   if ((pe->func_deinit = PyDict_GetItemString(pe->dict, "deinit")) == NULL) 
   {
      log_err("pythonmod: function deinit is missing in %s", pe->fname);
      PyGILState_Release(gil);
      return 0;
   }
   if ((pe->func_operate = PyDict_GetItemString(pe->dict, "operate")) == NULL) 
   {
      log_err("pythonmod: function operate is missing in %s", pe->fname);
      PyGILState_Release(gil);
      return 0;
   }
   if ((pe->func_inform = PyDict_GetItemString(pe->dict, "inform_super")) == NULL) 
   {
      log_err("pythonmod: function inform_super is missing in %s", pe->fname);
      PyGILState_Release(gil);
      return 0;
   }

   py_cfg = SWIG_NewPointerObj((void*) env->cfg, SWIGTYPE_p_config_file, 0);
   res = PyObject_CallFunction(pe->func_init, "iO", id, py_cfg);
   if (PyErr_Occurred()) 
   {
      log_err("pythonmod: Exception occurred in function init");
      PyErr_Print();
   }

   Py_XDECREF(res);
   Py_XDECREF(py_cfg);
   PyGILState_Release(gil);

   return 1;
}
Ejemplo n.º 16
0
void IvrPython::run(){
   FILE* fp;
   int retval;

#ifndef	IVR_PERL
   pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, 0);
#endif	//IVR_PERL
//   static PyThreadState* pyMainThreadState;
   fp = fopen((char*)fileName,"r");
   if(fp != NULL){
#ifndef	IVR_PERL
     PyMethodDef extIvrPython[] = {
       // media functions
       {"enqueueMediaFile", ivrEnqueueMediaFile, METH_VARARGS, "ivr: enqueue media file. "
	"filename: string, front : int = 1(default true)  "},
       {"emptyMediaQueue", ivrEmptyMediaQueue, METH_VARARGS, "ivr: empty the media queue."},
       {"startRecording", ivrStartRecording, METH_VARARGS, "ivr: start recording to file. filename : string."},
       {"stopRecording", ivrStopRecording, METH_VARARGS, "ivr: stop recording to file."},
#ifdef IVR_WITH_TTS
       {"say", ivrSay, METH_VARARGS, "ivr tts and enqueue. msg: string, front: boolean  "},
#endif //IVR_WITH_TTS
       // DTMF functions
       {"enableDTMFDetection", ivrEnableDTMFDetection, METH_VARARGS, "enable DTMF detection. "
	"setCallback(onDTMF_FUNC, \"onDTMF\") first!"},
       {"disableDTMFDetection", ivrDisableDTMFDetection, METH_VARARGS, "disable DTMF detection permanently"},
       {"pauseDTMFDetection", ivrPauseDTMFDetection, METH_VARARGS, "pause DTMF detection temporarily, can be resumed"},
       {"resumeDTMFDetection", ivrResumeDTMFDetection, METH_VARARGS, "resume DTMF detection"},

       // informational
       {"getTime", ivrGetTime, METH_VARARGS, "Example Module"},
       {"getFrom", ivrGetFrom, METH_VARARGS, "Example Module"},
       {"getTo", ivrGetTo, METH_VARARGS, "Example Module"},
       {"getFromURI", ivrGetFromURI, METH_VARARGS, "Example Module"},
       {"getToURI", ivrGetToURI, METH_VARARGS, "Example Module"},
       {"getDomain", ivrGetDomain, METH_VARARGS, "Example Module"},

       // call transfer functions
       {"redirect", ivrRedirect, METH_VARARGS, "Example Module"},
       {"dialout", ivrDialout, METH_VARARGS, "Example Module"},

       // setting callbacks
       {"setCallback", setCallback, METH_VARARGS, "Example Module"},

       {"sleep", ivrSleep, METH_VARARGS, "Sleep n seconds, or until wakeUp"},
       {"usleep", ivrUSleep, METH_VARARGS, "Sleep n microseconds, or until wakeUp"},
       {"msleep", ivrmSleep, METH_VARARGS, "Sleep n milliseconds, or until wakeUp"},
       {"wakeUp", ivrWakeUp, METH_VARARGS, "wake Up from sleep"},

       // legacy from old ivr: sequential functions
       {"play", ivrPlay, METH_VARARGS, "play and wait for the end of the file (queue empty)"},
       {"record", ivrRecord, METH_VARARGS, "record maximum of time secs. Parameter: filename : string, timeout = 0 : int"},
       {"playAndDetect", ivrPlayAndDetect, METH_VARARGS, "play and wait for the end of the file (queue empty) or keypress"},
       {"detect", ivrDetect, METH_VARARGS, "detect until timeout Parameter: timeout = 0 : int"},
// for jitter/clock skew generation test only
// DONT CALL THIS FUNCTION
       {"mediaThreadUSleep", ivrMediaThreadUSleep, METH_VARARGS, "let mthr sleep, dont call this function"},

       {NULL, NULL, 0, NULL},
     };

     if(!Py_IsInitialized()){
       DBG("Start" SCRIPT_TYPE "\n");
       Py_Initialize();
       PyEval_InitThreads();
       pyMainThreadState = PyEval_SaveThread();
     }
     DBG("Start new" SCRIPT_TYPE "interpreter\n");
     PyEval_AcquireLock();
//     PyThreadState* pyThreadState;
     if ( (mainInterpreterThreadState = Py_NewInterpreter()) != NULL){

       PyObject* ivrPyInitModule = Py_InitModule(PY_MOD_NAME, extIvrPython);
       PyObject* ivrPythonPointer = PyCObject_FromVoidPtr((void*)this,NULL);
       if (ivrPythonPointer != NULL)
	 PyModule_AddObject(ivrPyInitModule, "ivrPythonPointer", ivrPythonPointer);
       
       Py_tracefunc tmp_t = pythonTrace;
       PyEval_SetTrace(tmp_t, PyCObject_FromVoidPtr((void*)this,NULL));
       if(!PyRun_SimpleFile(fp,(char*)fileName)){
	 fclose(fp);
	 retval = 0;// true;
       }
       else{
            PyErr_Print();
            ERROR("IVR" SCRIPT_TYPE "Error: Failed to run \"%s\"\n", (char*)fileName);
	    retval = -1;// false;
       }

       Py_EndInterpreter(mainInterpreterThreadState);
     }
     else{
       ERROR("IVR" SCRIPT_TYPE "Error: Failed to start new interpreter.\n");
     }
     PyEval_ReleaseLock();
#else	//IVR_PERL

	DBG("Start" SCRIPT_TYPE ", about to alloc\n");
	my_perl_interp = perl_alloc();
	printf("interp is %ld\n", (long) my_perl_interp);
	printf("filename is %s\n", fileName);
	DBG("finished alloc Perl, about to construct Perl\n");
	perl_construct(my_perl_interp);
	PL_exit_flags |= PERL_EXIT_DESTRUCT_END;
	char *embedding[] = { "", (char*)fileName};
	DBG("finished construct Perl, about to parse Perl\n");
	perl_parse(my_perl_interp, xs_init, 2, embedding, (char **)NULL);
	DBG("finished parse Perl, about to run Perl\n");
	SV *pivr = get_sv("Ivr::__ivrpointer__", TRUE);
	DBG("Ivr::__ivrpointer__ is %lx.\n", (unsigned long int) pivr);
	sv_setuv(pivr, (unsigned int) this);
	perl_run(my_perl_interp);
	DBG("finished run Perl, about to sleep 5 seconds to let callback event catch up\n");
	sleep(5);
	DBG("after sleep, about to destruct\n");
	perl_destruct(my_perl_interp);
	DBG("finished destruct Perl, about to free\n");
	perl_free(my_perl_interp);
#endif	//IVR_PERL
   }
   else{
     ERROR("IVR" SCRIPT_TYPE "Error: Can not open file \"%s\"\n",(char*) fileName);
     retval = -1;// false;
   }
   DBG("IVR: run finished. stopping rtp stream...\n");
   pAmSession->rtp_str.pause();
}
Ejemplo n.º 17
0
/*
 * returns an error code if initialization fails
 */
int init_with_instance(HMODULE hmod, char *frozen)
{
	int rc;
	if (!_LocateScript(hmod))
		return 255;

	if (!_LoadPythonDLL(hmod))
		return 255;
	if (p_script_info->unbuffered) {
#if defined(MS_WINDOWS) || defined(__CYGWIN__)
		_setmode(fileno(stdin), O_BINARY);
		_setmode(fileno(stdout), O_BINARY);
#endif
#ifdef HAVE_SETVBUF
		setvbuf(stdin,	(char *)NULL, _IONBF, BUFSIZ);
		setvbuf(stdout, (char *)NULL, _IONBF, BUFSIZ);
		setvbuf(stderr, (char *)NULL, _IONBF, BUFSIZ);
#else /* !HAVE_SETVBUF */
		setbuf(stdin,  (char *)NULL);
		setbuf(stdout, (char *)NULL);
		setbuf(stderr, (char *)NULL);
#endif /* !HAVE_SETVBUF */
	}

	if (getenv("PY2EXE_VERBOSE"))
		Py_VerboseFlag = atoi(getenv("PY2EXE_VERBOSE"));
	else
		Py_VerboseFlag = 0;

	Py_IgnoreEnvironmentFlag = 1;
	Py_NoSiteFlag = 1;
	Py_OptimizeFlag = p_script_info->optimize;

	Py_SetProgramName(modulename);

	calc_path();

	if (!Py_IsInitialized()) {
		// First time round and the usual case - set sys.path
		// statically.
		rc = set_path_early();
		if (rc != 0)
			return rc;
	
	//	printf("Path before Py_Initialize(): %s\n", Py_GetPath());
	
		Py_Initialize();
	//	printf("Path after Py_Initialize(): %s\n", PyString_AsString(PyObject_Str(PySys_GetObject("path"))));
	} else {
		// Python already initialized.  This likely means there are
		// 2 py2exe based apps in the same process (eg, 2 COM objects
		// in a single host, 2 ISAPI filters in the same site, ...)
		// Until we get a better answer, add what we need to sys.path
		rc = set_path_late();
		if (rc != 0)
			return rc;
	}
	/* Set sys.frozen so apps that care can tell.
	   If the caller did pass NULL, sys.frozen will be set zo True.
	   If a string is passed this is used as the frozen attribute.
	   run.c passes "console_exe", run_w.c passes "windows_exe",
	   run_dll.c passes "dll"
	   This falls apart when you consider that in some cases, a single
	   process may end up with two py2exe generated apps - but still, we
	   reset frozen to the correct 'current' value for the newly
	   initializing app.
	*/
	if (frozen == NULL)
		PySys_SetObject("frozen", PyBool_FromLong(1));
	else {
		PyObject *o = PyString_FromString(frozen);
		if (o) {
			PySys_SetObject("frozen", o);
			Py_DECREF(o);
		}
	}

	_TryLoadZlib(hmod);

	return 0;
}
Ejemplo n.º 18
0
int main(int argc, char** argv)
{
  int i;
  int count=0;
  int buf;
  char* cube_str;
  //  char* formula;
  char* cube_info;
  int len_cube;
  printf("oktogo");
  Py_Initialize();
  if (Py_IsInitialized()) {    
    PySys_SetArgv(argc, argv);


    PyObject* solver = PyImport_ImportModule("solver");
    if(solver) {
      PyObject* get_cube = PyObject_GetAttrString(solver, "send_cube");
      if(get_cube) {
	
	PyObject *d = PyObject_CallFunction(get_cube, NULL);
	if (PyString_Check(d)) {
	  cube_info =PyString_AsString(d);
	}
	Py_XDECREF(d);
	Py_XDECREF(get_cube);

      

      }	
    Py_XDECREF(solver);
    }
  
  Py_Finalize();
    }


        printf("%s\n",cube_info);
  


        len_cube=strlen(cube_info);
  
  
	printf("%d\n",len_cube);
      
  for(i=0;i<8;i++){
    corner_permu[i]=cube_info[i];
  }
  count+=8;
  for(i=0;i<8;i++){
    char moji=cube_info[i+count];
    switch(moji){
    case 't':
      buf=-1;
      break;
    case '0':
      buf=0;
      break;
    case '1':
      buf=1;
      break;
    }
    corner_ori[i]=buf;
  }
  count+=8;
  for(i=0;i<12;i++){
    switch(cube_info[i+count]){
    case('1'):
      buf=1;
      break;
    case('2'):
      buf=2;
      break;
    case('3'):
      buf=3;
      break;
    case('4'):
      buf=4;
      break;
    case('5'):
      buf=5;
      break;
    case('6'):
      buf=6;
      break;
    case('7'):
      buf=7;
      break;
    case('8'):
      buf=8;
      break;
    case('9'):
      buf=9;
      break;
    case('x'):
      buf=10;
      break;
    case('y'):
      buf=11;
      break;
    case('z'):
      buf=12;
      break;
    }
    edge_permu[i]=buf;
  }
  count+=12;
  for(i=0;i<12;i++){
    switch(cube_info[i+count]){
    case('0'):
      buf=0;
      break;
    case('1'):
      buf=1;
      break;
    }
    edge_ori[i]=buf;
  }
  count+=12;
  printf("%d\n",count);


  char *formula=malloc((len_cube-count)*sizeof(char));
  for(i=0;i<len_cube-count;i++){
    formula[i]=cube_info[i+count];
  }
  printf("%s",formula);




  glutInit(&argc,argv);
  glutInitDisplayMode(GLUT_DOUBLE|GLUT_RGBA|GLUT_DEPTH);
  glutInitWindowSize(640,480);
  glutInitWindowPosition(50,50);
  glutCreateWindow("cube");

  init();
  //  rotate('U');
  //rotate('R');
  //rotate('D');
  //rotate('R');

  glutDisplayFunc(display);
  glutReshapeFunc(reshape);
  glutKeyboardFunc(keyboard);
  glutIdleFunc(idle);
  glutMouseFunc(mouse);
  glutMotionFunc(motion);
  glutMainLoop();
  
  return 0;
}
Ejemplo n.º 19
0
int
weechat_plugin_init (struct t_weechat_plugin *plugin, int argc, char *argv[])
{
    struct t_plugin_script_init init;

    weechat_python_plugin = plugin;

    /*
     * hook info to get path to python 2.x interpreter
     * (some scripts using hook_process need that)
     */
    weechat_python_set_python2_bin ();
    weechat_hook_info ("python2_bin",
                       N_("path to python 2.x interpreter"),
                       NULL,
                       &weechat_python_info_cb, NULL);

    /* init stdout/stderr buffer */
    python_buffer_output[0] = '\0';

    PyImport_AppendInittab("weechat",
                           &weechat_python_init_module_weechat);

    Py_Initialize ();
    if (Py_IsInitialized () == 0)
    {
        weechat_printf (NULL,
                        weechat_gettext ("%s%s: unable to launch global "
                                         "interpreter"),
                        weechat_prefix ("error"), PYTHON_PLUGIN_NAME);
        return WEECHAT_RC_ERROR;
    }

    /* PyEval_InitThreads(); */
    /* python_mainThreadState = PyThreadState_Swap(NULL); */
    python_mainThreadState = PyEval_SaveThread();
    /* PyEval_ReleaseLock (); */

    if (!python_mainThreadState)
    {
        weechat_printf (NULL,
                        weechat_gettext ("%s%s: unable to get current "
                                         "interpreter state"),
                        weechat_prefix ("error"), PYTHON_PLUGIN_NAME);
        return WEECHAT_RC_ERROR;
    }

    init.callback_command = &weechat_python_command_cb;
    init.callback_completion = &weechat_python_completion_cb;
    init.callback_hdata = &weechat_python_hdata_cb;
    init.callback_infolist = &weechat_python_infolist_cb;
    init.callback_signal_debug_dump = &weechat_python_signal_debug_dump_cb;
    init.callback_signal_debug_libs = &weechat_python_signal_debug_libs_cb;
    init.callback_signal_buffer_closed = &weechat_python_signal_buffer_closed_cb;
    init.callback_signal_script_action = &weechat_python_signal_script_action_cb;
    init.callback_load_file = &weechat_python_load_cb;

    python_quiet = 1;
    plugin_script_init (weechat_python_plugin, argc, argv, &init);
    python_quiet = 0;

    plugin_script_display_short_list (weechat_python_plugin,
                                      python_scripts);

    /* init OK */
    return WEECHAT_RC_OK;
}
Ejemplo n.º 20
0
	void PyInterpreter::initialize()
	{
		valid_ = false;
		start_log_.clear();

		// finalize the interpreter if it is already running
		if (Py_IsInitialized())
		{
			Py_Finalize();
		}

		// on some platforms, we have to point the system to our own python packages
#ifdef BALL_OS_WINDOWS
		// TODO: decide through a registry key which python version to use
		Py_SetProgramName(BALL_PATH "/bin/python.exe");
#endif

		// initialize the interpreter
		Py_Initialize();

		// get a borrowed reference to the main - module
		PyObject* main_module = PyImport_AddModule("__main__");

		if (main_module == 0) 
		{
			Log.error() << "Python intialization failed: could not add \"__main__\" module! No Python support available." << std::endl;
			return;
		}

		// and create a valid context for our further Python - calls
		context_ = PyModule_GetDict(main_module);
	
		if (context_ == 0) 
		{
			Log.error() << "Could not get valid context for Python module \"__main__\"! No Python support available." << std::endl;
			return;
		}

		// import sys
		runSingleString_("import sys", Py_single_input);
		start_log_ += error_message_;

		// Add the BALL library path to the Python search path
		// to make sure Python can find the BALL extensions.
		Path p;

#ifndef BALL_COMPILER_MSVC
		runSingleString_("sys.path.append(\"" BALL_PATH "/lib/" "\")", Py_single_input);

#ifdef BALL_OS_DARWIN
	// on MacOS, try to find the python packages in the frameworks directory of our bundle
	String site_path = String(p.find("../Frameworks"));
	if (site_path != "")
		sys_path_.push_back(site_path);
#endif

#else
		// first, make sure that the site packages of our python installation will be found
		String site_path = String(p.find("Python\\lib"));
		site_path.trim();
		while (site_path.substitute("\\", "/") != String::EndPos) {};
		if (site_path != "")
			sys_path_.push_back(site_path);

		// on windows, we put our python packages one step above the data directory
		String python_path = String(p.find("..\\BALL.py")).before("BALL.py");
		python_path.trim();
		while (python_path.substitute("\\", "/") != String::EndPos) {};

		if (python_path != "")
			sys_path_.push_back(python_path);
#endif
		// try to locate startup.py as well
		String python_startup_path = String(p.find("startup.py")).before("startup.py");
		python_startup_path.trim();
		while (python_startup_path.substitute("\\", "/") != String::EndPos) {};

		if (python_startup_path != "")
			sys_path_.push_back(python_startup_path);

		start_log_ += error_message_;

		// Add additional paths (user-defined) to the end of the search path.
		// 
		std::vector<String>::const_iterator it(sys_path_.begin());
		for (; it != sys_path_.end(); ++it)
		{
			runSingleString_("sys.path.append(\"" + *it + "\")", Py_single_input);
			start_log_ += error_message_;
		}

		// import the site module, and the one required for the output redirection
		runSingleString_("import site, cStringIO", Py_single_input);
		start_log_ += error_message_;

		PyObject *sip_module = PyImport_ImportModule("sip");
		if (sip_module == 0) 
		{
			Log.error() << "Could not import Python module \"sip\"! No Python support available." << std::endl;
			return;
		}

		Py_DECREF(sip_module);

		// make sure that we found the correct sip version
		valid_ = true;

		run("import sip", valid_);
		const unsigned int module_sip_version = run("print(sip.SIP_VERSION)", valid_).trim().toUnsignedInt();
		const String module_sip_version_str = run("print(sip.SIP_VERSION_STR)", valid_).trim();

		const unsigned int module_major_minor = module_sip_version & 0xFFFFFF00;
		const unsigned int module_bugfix      = module_sip_version & 0x000000FF;
		const unsigned int ball_major_minor   = BALL_SIP_VERSION   & 0xFFFFFF00;
		const unsigned int ball_bugfix        = BALL_SIP_VERSION   & 0x000000FF;

		if ((module_major_minor != ball_major_minor) || (module_bugfix < ball_bugfix))
		{
			String sip_module_path = run("print(sip)", valid_).trim();

			error_message_ += "ERROR: Version of imported sip module is not compatible with the version BALL was built against.\n"
			                  "If BALL was compiled using SIP version x.y.z then it can be used with any SIP version x.y.z' where "
												"z' >= z.\n";
			error_message_ += "Got (from " + sip_module_path + ") " + module_sip_version_str + "; Expected " + BALL_SIP_VERSION_STR +"\n";

			Log.error() << error_message_ << std::endl;

			start_log_ += error_message_;

			valid_ = false;

			return;
		}

		// import the BALL module
		start_log_ += run("from BALL import *", valid_);

		if (!valid_) 
		{
			Log.error() << "Could not import the BALL library! No Python support available." << std::endl;
		}
	}
Ejemplo n.º 21
0
//-------------------------------------------------------------------------------------
bool Script::install(const wchar_t* pythonHomeDir, std::wstring pyPaths, 
	const char* moduleName, COMPONENT_TYPE componentType)
{
	std::wstring pySysPaths = SCRIPT_PATH;
	wchar_t* pwpySysResPath = strutil::char2wchar(const_cast<char*>(Resmgr::getSingleton().getPySysResPath().c_str()));
	strutil::kbe_replace(pySysPaths, L"../../res/", pwpySysResPath);
	pyPaths += pySysPaths;
	free(pwpySysResPath);

#if KBE_PLATFORM == PLATFORM_WIN32
	Py_SetPythonHome(const_cast<wchar_t*>(pythonHomeDir));								// 先设置python的环境变量
#else
	std::wstring fs = L";";
	std::wstring rs = L":";
	size_t pos = 0; 

	while(true)
	{ 
		pos = pyPaths.find(fs, pos);
		if (pos == std::wstring::npos) break;
		pyPaths.replace(pos, fs.length(), rs);
	}  

	Py_SetPath(pyPaths.c_str()); 
	char* tmpchar = strutil::wchar2char(const_cast<wchar_t*>(pyPaths.c_str()));
	DEBUG_MSG(boost::format("Script::install: paths=%1%.\n") % tmpchar);
	free(tmpchar);
	
#endif
	// Initialise python
	// Py_VerboseFlag = 2;
	Py_FrozenFlag = 1;

	// Warn if tab and spaces are mixed in indentation.
	// Py_TabcheckFlag = 1;
	Py_NoSiteFlag = 1;
	Py_IgnoreEnvironmentFlag = 1;
	Py_Initialize();                      											// python解释器的初始化  
    if (!Py_IsInitialized())
    {
    	ERROR_MSG("Script::install::Py_Initialize is failed!\n");
        return false;
    } 

#if KBE_PLATFORM == PLATFORM_WIN32
	PySys_SetPath(pyPaths.c_str());
#endif

	PyObject *m = PyImport_AddModule("__main__");

	module_ = PyImport_AddModule(moduleName);										// 添加一个脚本基础模块
	if (module_ == NULL)
		return false;
	
	const char* componentName = COMPONENT_NAME_EX(componentType);
	if (PyModule_AddStringConstant(module_, "component", componentName))
	{
		ERROR_MSG(boost::format("Script::init: Unable to set KBEngine.component to %1%\n") %
			componentName );
		return false;
	}
	
	// 注册产生uuid方法到py
	APPEND_SCRIPT_MODULE_METHOD(module_,		genUUID64,			__py_genUUID64,					METH_VARARGS,			0);

	if(!install_py_dlls())
	{
		ERROR_MSG("Script::init: install_py_dlls() is failed!\n");
		return false;
	}

#ifndef KBE_SINGLE_THREADED
	s_pOurInitTimeModules = PyDict_Copy( PySys_GetObject( "modules" ) );
	s_pMainThreadState = PyThreadState_Get();
	s_defaultContext = s_pMainThreadState;
	PyEval_InitThreads();

	KBEConcurrency::setMainThreadIdleFunctions(
		&Script::releaseLock, &Script::acquireLock );
#endif

	ScriptStdOutErr::installScript(NULL);											// 安装py重定向模块
	ScriptStdOutErrHook::installScript(NULL);

	static struct PyModuleDef moduleDesc =   
	{  
			 PyModuleDef_HEAD_INIT,  
			 moduleName,  
			 "This module is created by KBEngine!",  
			 -1,  
			 NULL  
	};  

	PyModule_Create(&moduleDesc);													// 初始化基础模块
	PyObject_SetAttrString(m, moduleName, module_);									// 将模块对象加入main

	pyStdouterr_ = new ScriptStdOutErr();											// 重定向python输出
	pyStdouterrHook_ = new ScriptStdOutErrHook();
	
	if(!pyStdouterr_->install()){													// 安装py重定向脚本模块
		ERROR_MSG("Script::install::pyStdouterr_->install() is failed!\n");
		SCRIPT_ERROR_CHECK();
		return false;
	}
	
	Pickler::initialize();
	PyProfile::initialize(this);
	PyStruct::initialize();
	Copy::initialize();
	SCRIPT_ERROR_CHECK();

	math::installModule("Math");
	INFO_MSG("Script::install is successfully!\n");
	return installExtraModule("KBExtra");
}
Ejemplo n.º 22
0
	bool PyInterpreter::isInitialized()
	{
		return Py_IsInitialized();
	}
Ejemplo n.º 23
0
void python_deinit() {
	if (Py_IsInitialized()) {
		Py_Finalize();
	}
}
Ejemplo n.º 24
0
PyObject *
PyModule_Create2(struct PyModuleDef* module, int module_api_version)
{
    PyObject *d, *v, *n;
    PyMethodDef *ml;
    const char* name;
    PyModuleObject *m;
    if (!Py_IsInitialized())
        Py_FatalError("Interpreter not initialized (version mismatch?)");
    if (PyType_Ready(&moduledef_type) < 0)
        return NULL;
    if (module->m_base.m_index == 0) {
        max_module_number++;
        Py_REFCNT(module) = 1;
        Py_TYPE(module) = &moduledef_type;
        module->m_base.m_index = max_module_number;
    }
    name = module->m_name;
    if (module_api_version != PYTHON_API_VERSION) {
        char message[512];
        PyOS_snprintf(message, sizeof(message),
                      api_version_warning, name,
                      PYTHON_API_VERSION, name,
                      module_api_version);
        if (PyErr_WarnEx(PyExc_RuntimeWarning, message, 1))
            return NULL;
    }
    /* Make sure name is fully qualified.

       This is a bit of a hack: when the shared library is loaded,
       the module name is "package.module", but the module calls
       PyModule_Create*() with just "module" for the name.  The shared
       library loader squirrels away the true name of the module in
       _Py_PackageContext, and PyModule_Create*() will substitute this
       (if the name actually matches).
    */
    if (_Py_PackageContext != NULL) {
        char *p = strrchr(_Py_PackageContext, '.');
        if (p != NULL && strcmp(module->m_name, p+1) == 0) {
            name = _Py_PackageContext;
            _Py_PackageContext = NULL;
        }
    }
    if ((m = (PyModuleObject*)PyModule_New(name)) == NULL)
        return NULL;

    if (module->m_size > 0) {
        m->md_state = PyMem_MALLOC(module->m_size);
        if (!m->md_state) {
            PyErr_NoMemory();
            Py_DECREF(m);
            return NULL;
        }
        memset(m->md_state, 0, module->m_size);
    }

    d = PyModule_GetDict((PyObject*)m);
    if (module->m_methods != NULL) {
        n = PyUnicode_FromString(name);
        if (n == NULL)
            return NULL;
        for (ml = module->m_methods; ml->ml_name != NULL; ml++) {
            if ((ml->ml_flags & METH_CLASS) ||
                (ml->ml_flags & METH_STATIC)) {
                PyErr_SetString(PyExc_ValueError,
                                "module functions cannot set"
                                " METH_CLASS or METH_STATIC");
                Py_DECREF(n);
                return NULL;
            }
            v = PyCFunction_NewEx(ml, (PyObject*)m, n);
            if (v == NULL) {
                Py_DECREF(n);
                return NULL;
            }
            if (PyDict_SetItemString(d, ml->ml_name, v) != 0) {
                Py_DECREF(v);
                Py_DECREF(n);
                return NULL;
            }
            Py_DECREF(v);
        }
        Py_DECREF(n);
    }
    if (module->m_doc != NULL) {
        v = PyUnicode_FromString(module->m_doc);
        if (v == NULL || PyDict_SetItemString(d, "__doc__", v) != 0) {
            Py_XDECREF(v);
            return NULL;
        }
        Py_DECREF(v);
    }
    m->md_def = module;
    return (PyObject*)m;
}
Ejemplo n.º 25
0
int pythonmod_init(struct module_env* env, int id)
{
   /* Initialize module */
   FILE* script_py = NULL;
   PyObject* py_init_arg, *res;
   PyGILState_STATE gil;
   int init_standard = 1;
#if PY_MAJOR_VERSION < 3
   PyObject* PyFileObject = NULL;
#endif

   struct pythonmod_env* pe = (struct pythonmod_env*)calloc(1, sizeof(struct pythonmod_env));
   if (!pe)
   {
      log_err("pythonmod: malloc failure");
      return 0;
   }

   env->modinfo[id] = (void*) pe;

   /* Initialize module */
   pe->fname = env->cfg->python_script;
   if(pe->fname==NULL || pe->fname[0]==0) {
      log_err("pythonmod: no script given.");
      return 0;
   }

   /* Initialize Python libraries */
   if (!Py_IsInitialized())
   {
#if PY_MAJOR_VERSION >= 3
      wchar_t progname[8];
      mbstowcs(progname, "unbound", 8);
#else
      char *progname = "unbound";
#endif
      Py_SetProgramName(progname);
      Py_NoSiteFlag = 1;
#if PY_MAJOR_VERSION >= 3
      PyImport_AppendInittab(SWIG_name, (void*)SWIG_init);
#endif
      Py_Initialize();
      PyEval_InitThreads();
      SWIG_init();
      pe->mainthr = PyEval_SaveThread();
   }

   gil = PyGILState_Ensure();

   /* Initialize Python */
   PyRun_SimpleString("import sys \n");
   PyRun_SimpleString("sys.path.append('.') \n");
   if(env->cfg->directory && env->cfg->directory[0]) {
      char wdir[1524];
      snprintf(wdir, sizeof(wdir), "sys.path.append('%s') \n",
      env->cfg->directory);
      PyRun_SimpleString(wdir);
   }
   PyRun_SimpleString("sys.path.append('"RUN_DIR"') \n");
   PyRun_SimpleString("sys.path.append('"SHARE_DIR"') \n");
   PyRun_SimpleString("import distutils.sysconfig \n");
   PyRun_SimpleString("sys.path.append(distutils.sysconfig.get_python_lib(1,0)) \n");
   if (PyRun_SimpleString("from unboundmodule import *\n") < 0)
   {
      log_err("pythonmod: cannot initialize core module: unboundmodule.py");
      PyGILState_Release(gil);
      return 0;
   }

   /* Check Python file load */
   /* uses python to open the file, this works on other platforms,
    * eg. Windows, to open the file in the correct mode for python */
#if PY_MAJOR_VERSION < 3
   PyFileObject = PyFile_FromString((char*)pe->fname, "r");
   script_py = PyFile_AsFile(PyFileObject);
#else
   script_py = _Py_fopen(pe->fname, "r");
#endif
   if (script_py == NULL)
   {
      log_err("pythonmod: can't open file %s for reading", pe->fname);
      PyGILState_Release(gil);
      return 0;
   }

   /* Load file */
   pe->module = PyImport_AddModule("__main__");
   pe->dict = PyModule_GetDict(pe->module);
   pe->data = Py_None;
   Py_INCREF(pe->data);
   PyModule_AddObject(pe->module, "mod_env", pe->data);

   /* TODO: deallocation of pe->... if an error occurs */

   if (PyRun_SimpleFile(script_py, pe->fname) < 0) {
      log_err("pythonmod: can't parse Python script %s", pe->fname);
      /* print the error to logs too, run it again */
      fseek(script_py, 0, SEEK_SET);
      /* we don't run the file, like this, because then side-effects
       *    s = PyRun_File(script_py, pe->fname, Py_file_input, 
       *        PyModule_GetDict(PyImport_AddModule("__main__")), pe->dict);
       * could happen (again). Instead we parse the file again to get
       * the error string in the logs, for when the daemon has stderr
       * removed.  SimpleFile run already printed to stderr, for then
       * this is called from unbound-checkconf or unbound -dd the user
       * has a nice formatted error.
      */
      /* ignore the NULL return of _node, it is NULL due to the parse failure
       * that we are expecting */
      (void)PyParser_SimpleParseFile(script_py, pe->fname, Py_file_input);
      log_py_err();
      PyGILState_Release(gil);
      return 0;
   }
#if PY_MAJOR_VERSION < 3
   Py_XDECREF(PyFileObject);
#else
   fclose(script_py);
#endif

   if ((pe->func_init = PyDict_GetItemString(pe->dict, "init_standard")) == NULL)
   {
      init_standard = 0;
      if ((pe->func_init = PyDict_GetItemString(pe->dict, "init")) == NULL)
      {
         log_err("pythonmod: function init is missing in %s", pe->fname);
         PyGILState_Release(gil);
         return 0;
      }
   }
   if ((pe->func_deinit = PyDict_GetItemString(pe->dict, "deinit")) == NULL)
   {
      log_err("pythonmod: function deinit is missing in %s", pe->fname);
      PyGILState_Release(gil);
      return 0;
   }
   if ((pe->func_operate = PyDict_GetItemString(pe->dict, "operate")) == NULL)
   {
      log_err("pythonmod: function operate is missing in %s", pe->fname);
      PyGILState_Release(gil);
      return 0;
   }
   if ((pe->func_inform = PyDict_GetItemString(pe->dict, "inform_super")) == NULL)
   {
      log_err("pythonmod: function inform_super is missing in %s", pe->fname);
      PyGILState_Release(gil);
      return 0;
   }

   if (init_standard)
   {
      py_init_arg = SWIG_NewPointerObj((void*) env, SWIGTYPE_p_module_env, 0);
   }
   else
   {
      py_init_arg = SWIG_NewPointerObj((void*) env->cfg,
        SWIGTYPE_p_config_file, 0);
   }
   res = PyObject_CallFunction(pe->func_init, "iO", id, py_init_arg);
   if (PyErr_Occurred())
   {
      log_err("pythonmod: Exception occurred in function init");
      log_py_err();
      Py_XDECREF(res);
      Py_XDECREF(py_init_arg);
      PyGILState_Release(gil);
      return 0;
   }

   Py_XDECREF(res);
   Py_XDECREF(py_init_arg);
   PyGILState_Release(gil);

   return 1;
}
Ejemplo n.º 26
0
void
pbs_python_ext_start_interpreter(
	struct python_interpreter_data *interp_data)
{
	static char func_id[] = "pbs_python_ext_start_interpreter";

#ifdef	PYTHON           /* -- BEGIN ONLY IF PYTHON IS CONFIGURED -- */

	struct stat sbuf;
	char pbs_python_home[MAXPATHLEN+1];
	char pbs_python_destlib[MAXPATHLEN+1];
	int  evtype;
	int  rc;

	/*
	 * initialize the convenience global pbs_python_daemon_name, as it is
	 * used everywhere
	 */

	pbs_python_daemon_name = interp_data->daemon_name;

	/* Need to make logging less verbose if pbs_python command */
	/* used, since it can get called many times in a pbs daemon, */
	/* and it would litter that daemon's logs */
	if (IS_PBS_PYTHON_CMD(pbs_python_daemon_name))
		evtype = PBSEVENT_DEBUG3;
	else
		evtype = PBSEVENT_DEBUG2;

	memset((char *)pbs_python_home, '\0', MAXPATHLEN+1);
	memset((char *)pbs_python_destlib, '\0', MAXPATHLEN+1);

	snprintf(pbs_python_home, MAXPATHLEN, "%s/python",
		pbs_conf.pbs_exec_path);
	snprintf(pbs_python_destlib, MAXPATHLEN, "%s/lib64/python/altair",
		pbs_conf.pbs_exec_path);
	rc = stat(pbs_python_destlib, &sbuf);
	if (rc != 0) {
		snprintf(pbs_python_destlib, MAXPATHLEN, "%s/lib/python/altair",
			pbs_conf.pbs_exec_path);
		rc = stat(pbs_python_destlib, &sbuf);
	}
	if (rc != 0) {
		log_err(-1, func_id,
			"--> PBS Python library directory not found <--");
		return;
	}
	if (!S_ISDIR(sbuf.st_mode)) {
		log_err(-1, func_id,
			"--> PBS Python library path is not a directory <--");
		return;
	}

	if (interp_data) {
		interp_data->init_interpreter_data(interp_data); /* to be safe */
		if (interp_data->interp_started) {
			log_event(evtype, PBS_EVENTCLASS_SERVER,
				LOG_INFO, interp_data->daemon_name,
				"--> Python interpreter already started <--");
			return;
		}
	} else { /* we need to allocate memory */
		log_err(-1, func_id,
			"--> Passed NULL for interpreter data <--");
		return;
	}

	Py_NoSiteFlag = 1;
	Py_FrozenFlag = 1;
	Py_OptimizeFlag = 2;            /* TODO make this a compile flag variable */
	Py_IgnoreEnvironmentFlag = 1;   /* ignore PYTHONPATH and PYTHONHOME */
	if (file_exists(pbs_python_home))
		Py_SetPythonHome(pbs_python_home);

	/* we make sure our top level module is initialized */
	if ((PyImport_ExtendInittab(pbs_python_inittab_modules) != 0)) {
		log_err(-1, "PyImport_ExtendInittab",
			"--> Failed to initialize Python interpreter <--");
		return;
	}


	Py_InitializeEx(1);  /* arg '1' means to not skip init of signals -    */
	/* we want signals to propagate to the executing  */
	/* Python script to be able to interrupt it       */

	if (Py_IsInitialized()) {
		interp_data->interp_started = 1; /* mark python as initialized */
		/* print only the first five characters, TODO check for NULL? */
		snprintf(log_buffer, LOG_BUF_SIZE-1,
			"--> Python Interpreter started, compiled with version:'%.*s' <--",
			5, Py_GetVersion());
		log_buffer[LOG_BUF_SIZE-1] = '\0';
		log_event(evtype, PBS_EVENTCLASS_SERVER,
			LOG_INFO, interp_data->daemon_name, log_buffer);
	} else {
		log_err(-1, "Py_InitializeEx",
			"--> Failed to initialize Python interpreter <--");
		goto ERROR_EXIT;
	}
	/*
	 * Add Altair python module directory to sys path. NOTE:
	 *  PBS_PYTHON_MODULE_DIR is a command line define, also insert
	 * standard required python modules
	 */
	if (pbs_python_modify_syspath(pbs_python_destlib, -1) == -1) {
		snprintf(log_buffer, LOG_BUF_SIZE-1,
			"could not insert %s into sys.path shutting down",
			pbs_python_destlib);
		log_buffer[LOG_BUF_SIZE-1] = '\0';
		log_err(-1, func_id, log_buffer);
		goto ERROR_EXIT;
	}

	/*
	 * At this point it is safe to load the available server types from
	 * the python modules. since the syspath is setup correctly
	 */
	if ((pbs_python_load_python_types(interp_data) == -1)) {
		log_err(-1, func_id, "could not load python types into the interpreter");
		goto ERROR_EXIT;
	}

	interp_data->pbs_python_types_loaded = 1; /* just in case */
	return;

ERROR_EXIT:
	pbs_python_ext_shutdown_interpreter(interp_data);
	return;
#else  /* !PYTHON */
	log_event(PBSEVENT_SYSTEM|PBSEVENT_ADMIN |
		PBSEVENT_DEBUG, PBS_EVENTCLASS_SERVER,
		LOG_INFO, "start_python",
		"--> Python interpreter not built in <--");
	return;
#endif /* PYTHON */
}
Ejemplo n.º 27
0
void
pbs_python_ext_quick_start_interpreter(void)
{
	static char func_id[] = "pbs_python_ext_quick_start_interpreter";

#ifdef	PYTHON           /* -- BEGIN ONLY IF PYTHON IS CONFIGURED -- */

	char pbs_python_home[MAXPATHLEN+1];
	char pbs_python_destlib[MAXPATHLEN+1];

	memset((char *)pbs_python_home, '\0', MAXPATHLEN+1);
	memset((char *)pbs_python_destlib, '\0', MAXPATHLEN+1);

	snprintf(pbs_python_home, MAXPATHLEN, "%s/python",
		pbs_conf.pbs_exec_path);
	snprintf(pbs_python_destlib, MAXPATHLEN, "%s/lib/python/altair",
		pbs_conf.pbs_exec_path);

	Py_NoSiteFlag = 1;
	Py_FrozenFlag = 1;
	Py_OptimizeFlag = 2;            /* TODO make this a compile flag variable */
	Py_IgnoreEnvironmentFlag = 1;   /* ignore PYTHONPATH and PYTHONHOME */
	if (file_exists(pbs_python_home))
		Py_SetPythonHome(pbs_python_home);

	/* we make sure our top level module is initialized */
	if ((PyImport_ExtendInittab(pbs_python_inittab_modules) != 0)) {
		log_err(-1, "PyImport_ExtendInittab",
			"--> Failed to initialize Python interpreter <--");
		return;
	}

	Py_InitializeEx(0);  /* SKIP initialization of signals */

	if (Py_IsInitialized()) {
		snprintf(log_buffer, LOG_BUF_SIZE-1,
			"--> Python Interpreter quick started, compiled with version:'%.*s' <--",
			5, Py_GetVersion());
		log_buffer[LOG_BUF_SIZE-1] = '\0';
		log_event(PBSEVENT_SYSTEM|PBSEVENT_ADMIN |
			PBSEVENT_DEBUG, PBS_EVENTCLASS_SERVER,
			LOG_INFO, func_id, log_buffer);
	} else {
		log_err(-1, "Py_InitializeEx",
			"--> Failed to quick initialize Python interpreter <--");
		goto ERROR_EXIT;
	}
	/*
	 * Add Altair python module directory to sys path. NOTE:
	 *  PBS_PYTHON_MODULE_DIR is a command line define, also insert
	 * standard required python modules
	 */
	if (pbs_python_modify_syspath(pbs_python_destlib, -1) == -1) {
		snprintf(log_buffer, LOG_BUF_SIZE-1,
			"could not insert %s into sys.path shutting down",
			pbs_python_destlib);
		log_buffer[LOG_BUF_SIZE-1] = '\0';
		log_err(-1, func_id, log_buffer);
		goto ERROR_EXIT;
	}

	snprintf(log_buffer, LOG_BUF_SIZE-1,
		"--> Inserted Altair PBS Python modules dir '%s' <--",
		pbs_python_destlib);
	log_buffer[LOG_BUF_SIZE-1] = '\0';
	log_event(PBSEVENT_SYSTEM|PBSEVENT_ADMIN |
		PBSEVENT_DEBUG, PBS_EVENTCLASS_SERVER,
		LOG_INFO, func_id, log_buffer);

	return;

ERROR_EXIT:
	pbs_python_ext_quick_shutdown_interpreter();
	return;
#else   /* !PYTHON */
	log_event(PBSEVENT_SYSTEM|PBSEVENT_ADMIN |
		PBSEVENT_DEBUG, PBS_EVENTCLASS_SERVER,
		LOG_INFO, "start_python",
		"--> Python interpreter not built in <--");
	return;
#endif  /* PYTHON */

}
Ejemplo n.º 28
0
BOOL check_init()
{
	BOOL ok = TRUE; // if already initialized all is good.
	if (!have_init) {
		EnterCriticalSection(&csInit);
		// Check the flag again - another thread may have beat us to it!
		if (!have_init) {

			PyGILState_STATE restore_state = PyGILState_UNLOCKED;
			PyObject *frozen;
			char dll_path[1024];
			char *slash;

			ok = FALSE; // must be reset after good init.
			// We must ensure Python is loaded, and therefore the
			// function pointers are non-NULL, before we can check
			// if Python is initialized!  Further, as our
			// ISAPI dll depends on python, we must load Python
			// before loading our module.
			if (!_LoadPythonDLL(gInstance))
				goto done;

			// Find and load the pyisapi DLL.
			GetModuleFileName(gInstance, dll_path, sizeof(dll_path)/sizeof(dll_path[0]));
			slash = strrchr(dll_path, '\\');
			if (slash) {
				// insert an underscore.
				char *pos_move = dll_path + strlen(dll_path);
				while (pos_move > slash) {
					*(pos_move+1) = *pos_move;
					pos_move --;
				}
				*(slash+1) = '_';
				hmodPyISAPI = LoadLibrary(dll_path);
				if (hmodPyISAPI) {
					pGetExtensionVersion = (__PROC__GetExtensionVersion)GetProcAddress(hmodPyISAPI, "GetExtensionVersion");
					pHttpExtensionProc = (__PROC__HttpExtensionProc)GetProcAddress(hmodPyISAPI, "HttpExtensionProc");
					pTerminateExtension = (__PROC__TerminateExtension)GetProcAddress(hmodPyISAPI, "TerminateExtension");
					pGetFilterVersion  = (__PROC__GetFilterVersion)GetProcAddress(hmodPyISAPI, "GetFilterVersion");
					pHttpFilterProc = (__PROC__HttpFilterProc)GetProcAddress(hmodPyISAPI, "HttpFilterProc");
					pTerminateFilter = (__PROC__TerminateFilter)GetProcAddress(hmodPyISAPI, "TerminateFilter");
					pPyISAPISetOptions = (__PROC__PyISAPISetOptions)GetProcAddress(hmodPyISAPI, "PyISAPISetOptions");
					pWriteEventLogMessage = (__PROC__WriteEventLogMessage)GetProcAddress(hmodPyISAPI, "WriteEventLogMessage");
				} else {
					SystemError(GetLastError(), "Failed to load the extension DLL");
				}
			} else {
				SystemError(GetLastError(), "Failed to locate my own DLL");
			}

			if (Py_IsInitialized && Py_IsInitialized())
				restore_state = PyGILState_Ensure();
			// a little DLL magic.  Set sys.frozen='dll'
			if (init_with_instance(gInstance, "dll") != 0) {
				PyGILState_Release(restore_state);
				goto done;
			}
			init_memimporter();
			frozen = PyInt_FromLong((LONG)gInstance);
			if (frozen) {
				PySys_SetObject("frozendllhandle", frozen);
				Py_DECREF(frozen);
			}
			// Now run the generic script - this always returns in a DLL.
			run_script();
			// Let the ISAPI extension know about the frozen environment.
			// (the ISAPI boot code currently has no way of talking directly
			// to the pyISAPI dll, so we fetch it directly from the py2exe
			// 'variable' which is already in module '__main__'.
			if (pPyISAPISetOptions) {
				PyObject *main = PyImport_ImportModule("__main__");
				if (main) {
					PyObject *name = PyObject_GetAttrString(main, "isapi_module_name");
					char *str;
					if (name && (str = PyString_AsString(name)))
						(*pPyISAPISetOptions)(str, TRUE);
					else
						PyErr_Clear(); // In case PyString_AsString fails
					Py_XDECREF(name);
				}
				Py_DECREF(main);
			}
			have_init = TRUE;
			PyGILState_Release(restore_state);
			ok = TRUE;
		}
done:
		LeaveCriticalSection(&csInit);
	}
	return ok;
}
Ejemplo n.º 29
0
static gboolean
peas_plugin_loader_python_initialize (PeasPluginLoader *loader)
{
  PeasPluginLoaderPython *pyloader = PEAS_PLUGIN_LOADER_PYTHON (loader);
  PeasPluginLoaderPythonPrivate *priv = GET_PRIV (pyloader);
  PyGILState_STATE state = 0;
  long hexversion;

  /* We can't support multiple Python interpreter states:
   * https://bugzilla.gnome.org/show_bug.cgi?id=677091
   */

  /* Python initialization */
  if (Py_IsInitialized ())
    {
      state = PyGILState_Ensure ();
    }
  else
    {
      Py_InitializeEx (FALSE);
      priv->must_finalize_python = TRUE;
    }

  hexversion = PyLong_AsLong (PySys_GetObject ((char *) "hexversion"));

#if PY_VERSION_HEX < 0x03000000
  if (hexversion >= 0x03000000)
#else
  if (hexversion < 0x03000000)
#endif
    {
      g_critical ("Attempting to mix incompatible Python versions");

      goto python_init_error;
    }

  /* Initialize PyGObject */
  pygobject_init (PYGOBJECT_MAJOR_VERSION,
                  PYGOBJECT_MINOR_VERSION,
                  PYGOBJECT_MICRO_VERSION);

  if (PyErr_Occurred ())
    {
      g_warning ("Error initializing Python Plugin Loader: "
                 "PyGObject initialization failed");

      goto python_init_error;
    }

  /* Initialize support for threads */
  pyg_enable_threads ();
  PyEval_InitThreads ();

  /* Only redirect warnings when python was not already initialized */
  if (!priv->must_finalize_python)
    pyg_disable_warning_redirections ();

  /* Must be done last, finalize() depends on init_failed */
  if (!peas_python_internal_setup (!priv->must_finalize_python))
    {
      /* Already warned */
      goto python_init_error;
    }

  if (!priv->must_finalize_python)
    PyGILState_Release (state);
  else
    priv->py_thread_state = PyEval_SaveThread ();

  return TRUE;

python_init_error:

  if (PyErr_Occurred ())
    PyErr_Print ();

  g_warning ("Please check the installation of all the Python "
             "related packages required by libpeas and try again");

  if (!priv->must_finalize_python)
    PyGILState_Release (state);

  priv->init_failed = TRUE;
  return FALSE;
}
Ejemplo n.º 30
0
peanoclaw::runners::PeanoClawLibraryRunner* pyclaw_peano_new (
  double initialMaximalMeshWidthScalar,
  double domainOffsetX0,
  double domainOffsetX1,
  double domainOffsetX2,
  double domainSizeX0,
  double domainSizeX1,
  double domainSizeX2,
  int subdivisionFactorX0,
  int subdivisionFactorX1,
  int subdivisionFactorX2,
  int unknownsPerSubcell,
  int auxiliarFieldsPerSubcell,
  int ghostlayerWidth,
  double initialTimestepSize,
  char* configurationFile,
  bool useDimensionalSplittingOptimization,
  bool reduceReductions,
  InitializationCallback initializationCallback,
  BoundaryConditionCallback boundaryConditionCallback,
  SolverCallback solverCallback,
  RefinementCriterionCallback refinementCriterionCallback,
  AddPatchToSolutionCallback addPatchToSolutionCallback,
  InterPatchCommunicationCallback interpolationCallback,
  InterPatchCommunicationCallback restrictionCallback,
  InterPatchCommunicationCallback fluxCorrectionCallback,
  bool enablePeanoLogging,
  int forkLevelIncrement,
  int *rank
) {
  peano::fillLookupTables();

#if defined(Parallel)
  char argv[2][256];
  memset(argv, 0, sizeof(char) * 2 * 256);
  int argc = 1;
  //sprintf(argv[0], "%s", "peanoclaw");
  peano::initParallelEnvironment(&argc,(char ***)&argv);
  peano::initSharedMemoryEnvironment();
#endif

  //Initialize Python
  _calledFromPython = Py_IsInitialized();

  if(_calledFromPython) {
    //Needed to take over the Python context from the calling process.
    _pythonState = PyGILState_Ensure();
  } else {
    Py_Initialize();
  }

  importArrays();

  //Initialize Logger
  static tarch::logging::Log _log("::pyclawBindings");
  logInfo("pyclaw_peano_new(...)", "Initializing Peano");

  configureLogFilter(enablePeanoLogging);

  //Numerics -- this object is copied to the runner and is stored there.
  peanoclaw::NumericsFactory numericsFactory;
  peanoclaw::Numerics* numerics = numericsFactory.createPyClawNumerics(
    initializationCallback,
    boundaryConditionCallback,
    solverCallback,
    refinementCriterionCallback,
    addPatchToSolutionCallback,
    interpolationCallback,
    restrictionCallback,
    fluxCorrectionCallback
  );

  _configuration = new peanoclaw::configurations::PeanoClawConfigurationForSpacetreeGrid;

  //Construct parameters
  tarch::la::Vector<DIMENSIONS, double> domainOffset = convertToVector(domainOffsetX0, domainOffsetX1, domainOffsetX2);
  tarch::la::Vector<DIMENSIONS, double> domainSize = convertToVector(domainSizeX0, domainSizeX1, domainSizeX2);
  
  tarch::la::Vector<DIMENSIONS, double> initialMinimalMeshWidth(initialMaximalMeshWidthScalar);
  tarch::la::Vector<DIMENSIONS, int> subdivisionFactor = convertToVector(subdivisionFactorX0, subdivisionFactorX1, subdivisionFactorX2);

  //Check parameters
  assertion1(tarch::la::greater(domainSizeX0, 0.0) && tarch::la::greater(domainSizeX1, 0.0), domainSize);
  if(initialMaximalMeshWidthScalar > domainSizeX0 || initialMaximalMeshWidthScalar > domainSizeX1) {
    logError("pyclaw_peano_new(...)", "Domainsize or initialMinimalMeshWidth not set properly.");
  }
  if(tarch::la::oneGreater(tarch::la::Vector<DIMENSIONS, int>(1), subdivisionFactor) ) {
    logError("pyclaw_peano_new(...)", "subdivisionFactor not set properly.");
  }
 
  //Create runner
  peanoclaw::runners::PeanoClawLibraryRunner* runner
    = new peanoclaw::runners::PeanoClawLibraryRunner(
    *_configuration,
    *numerics,
    domainOffset,
    domainSize,
    initialMinimalMeshWidth,
    subdivisionFactor,
    ghostlayerWidth,
    unknownsPerSubcell,
    auxiliarFieldsPerSubcell,
    initialTimestepSize,
    useDimensionalSplittingOptimization,
    reduceReductions,
    forkLevelIncrement
  );

  assertion(runner != 0);
 
#if defined(Parallel) 
  *rank = tarch::parallel::Node::getInstance().getRank();
#else
  *rank = 0;
#endif

  if(_calledFromPython) {
    PyGILState_Release(_pythonState);
  }

  return runner;
}