Esempio n. 1
0
bool CPythonHandler::LoadHandler(bool reload)
{
	char szErrBuf[1024];
	PyObject *m;
	CEnterLeavePython celp;
	m = PyImport_ImportModule(m_engine->m_module_name);
	if (m && reload) {
		PyObject *m_orig = m;
		m = PyImport_ReloadModule(m);
		Py_DECREF(m_orig);
	}
	if (!m) {
		_snprintf(szErrBuf, sizeof(szErrBuf)/sizeof(szErrBuf[0]), 
				  "Failed to import callback module '%s'", m_engine->m_module_name);
		ExtensionError(NULL, szErrBuf);
	}
	if (m) {
		Py_XDECREF(m_handler);
		if (!((m_handler = PyObject_CallMethod(m, (char *)m_namefactory, NULL)))) {
			_snprintf(szErrBuf, sizeof(szErrBuf)/sizeof(szErrBuf[0]), 
			          "Factory function '%s' failed", m_namefactory);
			ExtensionError(NULL, szErrBuf);
		}
		Py_DECREF(m);
	}
	return m_handler != NULL;
}
Esempio n. 2
0
bool PythonPlugin::loadOrReloadModule(ScriptEntry &script)
{
    const QByteArray name = script.name.toUtf8();

    if (script.module) {
        PySys_WriteStdout("-- Reloading %s\n", name.constData());

        PyObject *module = PyImport_ReloadModule(script.module);
        Py_DECREF(script.module);
        script.module = module;
    } else {
        PySys_WriteStdout("-- Loading %s\n", name.constData());
        script.module = PyImport_ImportModule(name.constData());
    }

    if (!script.module)
        return false;

    PyObject *pluginClass = findPluginSubclass(script.module);

    if (!pluginClass) {
        PySys_WriteStderr("Extension of tiled.Plugin not defined in "
                          "script: %s\n", name.constData());
        return false;
    }

    if (script.mapFormat) {
        script.mapFormat->setPythonClass(pluginClass);
    } else {
        script.mapFormat = new PythonMapFormat(name, pluginClass, *this);
        addObject(script.mapFormat);
    }

    return true;
}
Esempio n. 3
0
int PythonClass::refresh()
{
    if (m_module == 0) {
        log(ERROR, "bort");
        return -1;
    }
    PyObject * new_module = PyImport_ReloadModule(m_module);
    if (new_module == 0) {
        log(ERROR, String::compose("Error reloading python module \"%1\"",
                                   m_package));
        PyErr_Clear();
        return -1;
    }
    int ret = getClass(new_module);
    if (ret != 0) {
        log(ERROR, String::compose("Error finding python class \"%1\" in \"%2\"",
                                   m_type, m_package));
        return -1;
        // After reloading, but failing to get the class, I think the old class
        // should still work, but is no longer bound to the name. It won't
        // be collected at least until we release the reference we hold
        // in m_class
    }
    // We decref even though this is probably an identical pointer to the
    // module because the PyImport_ call returned a new reference
    Py_DECREF(m_module);
    if (m_module != new_module) {
        log(WARNING, String::compose("Python module \"%1.%2\" has changed "
                                     "its pointer on reload",
                                     m_package, m_type));
        m_module = new_module;
    }
    return 0;
}
Esempio n. 4
0
ProfPlugin*
python_plugin_create(const char *const filename)
{
    disable_python_threads();

    PyObject *p_module = g_hash_table_lookup(loaded_modules, filename);
    if (p_module) {
        p_module = PyImport_ReloadModule(p_module);
    } else {
        gchar *module_name = g_strndup(filename, strlen(filename) - 3);
        p_module = PyImport_ImportModule(module_name);
        if (p_module) {
            g_hash_table_insert(loaded_modules, strdup(filename), p_module);
        }
        g_free(module_name);
    }

    python_check_error();
    if (p_module) {
        ProfPlugin *plugin = malloc(sizeof(ProfPlugin));
        plugin->name = strdup(filename);
        plugin->lang = LANG_PYTHON;
        plugin->module = p_module;
        plugin->init_func = python_init_hook;
        plugin->on_start_func = python_on_start_hook;
        plugin->on_shutdown_func = python_on_shutdown_hook;
        plugin->on_unload_func = python_on_unload_hook;
        plugin->on_connect_func = python_on_connect_hook;
        plugin->on_disconnect_func = python_on_disconnect_hook;
        plugin->pre_chat_message_display = python_pre_chat_message_display_hook;
        plugin->post_chat_message_display = python_post_chat_message_display_hook;
        plugin->pre_chat_message_send = python_pre_chat_message_send_hook;
        plugin->post_chat_message_send = python_post_chat_message_send_hook;
        plugin->pre_room_message_display = python_pre_room_message_display_hook;
        plugin->post_room_message_display = python_post_room_message_display_hook;
        plugin->pre_room_message_send = python_pre_room_message_send_hook;
        plugin->post_room_message_send = python_post_room_message_send_hook;
        plugin->on_room_history_message = python_on_room_history_message_hook;
        plugin->pre_priv_message_display = python_pre_priv_message_display_hook;
        plugin->post_priv_message_display = python_post_priv_message_display_hook;
        plugin->pre_priv_message_send = python_pre_priv_message_send_hook;
        plugin->post_priv_message_send = python_post_priv_message_send_hook;
        plugin->on_message_stanza_send = python_on_message_stanza_send_hook;
        plugin->on_message_stanza_receive = python_on_message_stanza_receive_hook;
        plugin->on_presence_stanza_send = python_on_presence_stanza_send_hook;
        plugin->on_presence_stanza_receive = python_on_presence_stanza_receive_hook;
        plugin->on_iq_stanza_send = python_on_iq_stanza_send_hook;
        plugin->on_iq_stanza_receive = python_on_iq_stanza_receive_hook;
        plugin->on_contact_offline = python_on_contact_offline_hook;
        plugin->on_contact_presence = python_on_contact_presence_hook;
        plugin->on_chat_win_focus = python_on_chat_win_focus_hook;
        plugin->on_room_win_focus = python_on_room_win_focus_hook;

        allow_python_threads();
        return plugin;
    } else {
        allow_python_threads();
        return NULL;
    }
}
void LMF_ReloadPythonModule( PyObject* a_pModule){
	PyObject* pModule = PyImport_ReloadModule(a_pModule);
	if (pModule == NULL){
		std::cout << stderr << "Failed to reload, Python returned NULL.\n" << std::endl;
		return;
	}
	a_pModule = pModule;
}
Esempio n. 6
0
bool pybase::ReloadModule()
{
    SetArgs();
    PyObject *newmod;
    
    if(modname.length()) {

        if(module)
            newmod = PyImport_ReloadModule(module);
        else {
            // search in module path (TODO: check before if module is already present to avoid costly searching)
            char dir[1024];
            if(getmodulepath(modname.c_str(),dir,sizeof(dir)))
                AddToPath(dir);
//            else
//                PyErr_SetString(PyExc_ImportError,"Module not found in path");

#if 1
            // strip off eventual subpath from module name
            // it should already have been considered in the above AddToPath call
            size_t p = modname.rfind('/');
            const char *m;
            if(p == std::string::npos)
                m = modname.c_str();
            else {
                // reuse dir buffer...
                strcpy(dir,modname.c_str()+p+1);
                m = dir;
            }

            // module could also be loaded ok, even if it's not in the path (e.g. for internal stuff)
            newmod = PyImport_ImportModule((char *)m);
#else
            newmod = PyImport_ImportModule((char *)modname.c_str());
#endif
        }
    }
    else {
        // if no module name given, take py module
        newmod = module_obj; 
        Py_INCREF(newmod);
    }

    if(!newmod) {
        // unload faulty module
        UnimportModule();
        return false;
    }
    else {
        Py_XDECREF(module);
        module = newmod;
        dict = PyModule_GetDict(module); // borrowed
        return true;
    }
}
Esempio n. 7
0
/*!	
	Reloads Python interpreter and restarts loaded modules
*/
void reloadPython()
{
	PyObject *sysModule = PyImport_ImportModule( "sys" );
	PyObject *modules = PyObject_GetAttrString( sysModule, "modules" );

	// This is a dictionary, so iterate trough it and reload all contained modules
	PyObject *mList = PyDict_Items( modules );

	for( INT32 i = 0; i < PyList_Size( mList ); ++i )
		PyImport_ReloadModule( PyList_GetItem( mList, i ) );
}
/* Attempt to reload the playlist module */
static int playlist_python_reload(void) {
	PyObject* new_module;

	if (!(new_module = PyImport_ReloadModule(python_module))) {
		ices_log_error("Playlist module reload failed");
		PyErr_Print();

		return -1;
	}

	python_module = new_module;
	ices_log_debug("Playlist module reloaded");

	return 0;
}
Esempio n. 9
0
void set_dyn_pyhome(char *home, uint16_t pyhome_len) {


	char venv_version[15];
	PyObject *site_module;

	PyObject *pysys_dict = get_uwsgi_pydict("sys");

	PyObject *pypath = PyDict_GetItemString(pysys_dict, "path");
	if (!pypath) {
		PyErr_Print();
		exit(1);
	}

        // simulate a pythonhome directive
        if (uwsgi.wsgi_req->home_len > 0) {

                PyObject *venv_path = UWSGI_PYFROMSTRINGSIZE(uwsgi.wsgi_req->home, uwsgi.wsgi_req->home_len);

#ifdef UWSGI_DEBUG
                uwsgi_debug("setting dynamic virtualenv to %.*s\n", uwsgi.wsgi_req->home_len, uwsgi.wsgi_req->home);
#endif

                PyDict_SetItemString(pysys_dict, "prefix", venv_path);
                PyDict_SetItemString(pysys_dict, "exec_prefix", venv_path);

                venv_version[14] = 0;
                if (snprintf(venv_version, 15, "/lib/python%d.%d", PY_MAJOR_VERSION, PY_MINOR_VERSION) == -1) {
                        return;
                }

                // check here
                PyString_Concat(&venv_path, PyString_FromString(venv_version));

                if (PyList_Insert(pypath, 0, venv_path)) {
                        PyErr_Print();
                }

                site_module = PyImport_ImportModule("site");
                if (site_module) {
                        PyImport_ReloadModule(site_module);
                }

        }
}
Esempio n. 10
0
	void operator()(const boost::property_tree::ptree &msg) {
		try {
			boost::system::error_code ignore_ec;
			fs::path script_file("./avbot.py");
			std::time_t now_write_time = fs::last_write_time(script_file);
			if (fs::exists(script_file) && now_write_time != last_write_time_) {
				PyImport_ReloadModule(module_.ptr());
				file_changed_ = true;
				reload();
			}
			if (disable_python)
				return;
			std::stringstream ss;
			boost::property_tree::json_parser::write_json(ss, msg);
			pyhandler_.attr("on_message")(ss.str());
		}
		catch (...) {
			PyErr_Print();
		}
	}
Esempio n. 11
0
 PythonScript::PythonScript(const QString &fileName)
 {
   m_fileName = fileName;
   QFileInfo info(fileName);
   m_moduleName = info.baseName();
   m_lastModified = info.lastModified();
    
   try
   {
     prepareToCatchError();
     // try to import the module
     m_module = import(m_moduleName.toAscii().data());
     // import doesn't really reload the module if it was already loaded
     // to be save, we always reload it
     m_module = object(handle<>(PyImport_ReloadModule(m_module.ptr())));
   }
   catch(error_already_set const &)
   {
     catchError();
   }
 }
Esempio n. 12
0
  object PythonScript::module() const
  {
    QFileInfo fileInfo(m_fileName);

    if(fileInfo.lastModified() > m_lastModified)
    {
      try
      {
        prepareToCatchError();
        m_module = object(handle<>(PyImport_ReloadModule(m_module.ptr())));
      }
      catch(error_already_set const &)
      {
        catchError();
      }

      m_lastModified = fileInfo.lastModified();
    }

    return m_module;
  }
Esempio n. 13
0
// python.reload function: reload an existing module in maxscript
Value*
reload_cf( Value** arg_list, int count ) {
    // Step 1: make sure the arguments supplied are correct in count
    check_arg_count( python.reload, 1, count );

    // Step 2: evaluate the input item
    MXS_PROTECT(one_value_local(mxs_check));
    MXS_EVAL( arg_list[0], vl.mxs_check );

    // Step 3: make sure the item is a proper type
    if ( is_objectwrapper(vl.mxs_check) ) {
        PyImport_ReloadModule( ((ObjectWrapper*) vl.mxs_check)->object() );
        PY_ERROR_PROPAGATE_MXS_CLEANUP();
    }
    else {
        mprintf( _T("python.reload() error: you need to supply a valid python module to reload\n") );
    }

    MXS_CLEANUP();
    return &ok;
}
Esempio n. 14
0
	void operator()(channel_identifier cid, avbotmsg msg, send_avchannel_message_t sender, boost::asio::yield_context yield_context)
	{
		try {
			boost::system::error_code ignore_ec;
			fs::path script_file("./avbot.py");
			std::time_t now_write_time = fs::last_write_time(script_file);
			if (fs::exists(script_file) && now_write_time != last_write_time_) {
				PyImport_ReloadModule(module_.ptr());
				file_changed_ = true;
				reload();
			}
			if (disable_python)
				return;
			std::stringstream ss;
			auto json_msg = av_msg_make_json(cid, msg);
			json_msg.put("channel", channel_name_ );
			boost::property_tree::json_parser::write_json(ss, json_msg);
			pyhandler_.attr("on_message")(ss.str());
		}
		catch (...) {
			PyErr_Print();
		}
	}
Esempio n. 15
0
PyObject *                          /* returns module object named modname  */
PP_Load_Module(const char *modname)       /* modname can be "package.module" form */
{                                   /* reload just resets C extension mods  */
    /* 
     * 4 cases:
     * - module "__main__" has no file, and not prebuilt: fetch or make
     * - dummy modules have no files: don't try to reload them
     * - reload=on and already loaded (on sys.modules): "reload()" before use
     * - not loaded yet, or loaded but reload=off: "import" to fetch or load 
     */

    PyObject *module, *sysmods;                  
    modname = PP_Init(modname);                       /* default to __main__ */

    if (strcmp(modname, "__main__") == 0)             /* main: no file */
        return PyImport_AddModule(modname);           /* not increfd */

    sysmods = PyImport_GetModuleDict();               /* get sys.modules dict */
    module  = PyDict_GetItemString(sysmods, modname); /* mod in sys.modules? */
    
    if (module != NULL &&                             /* dummy: no file */
        PyModule_Check(module) && 
        PyDict_GetItemString(PyModule_GetDict(module), "__dummy__")) {
        return module;                                /* not increfd */
    }
    else
    if (PP_RELOAD && module != NULL && PyModule_Check(module)) {
        module = PyImport_ReloadModule(module);       /* reload file,run code */
        Py_XDECREF(module);                           /* still on sys.modules */
        return module;                                /* not increfd */
    }
    else {  
        module = PyImport_ImportModule(modname);      /* fetch or load module */
        Py_XDECREF(module);                           /* still on sys.modules */
        return module;                                /* not increfd */
    }
}
Esempio n. 16
0
static PyObject *blender_reload(PyObject *UNUSED(self), PyObject *module)
{
	PyObject *exception, *err, *tb;
	PyObject *newmodule = NULL;
	int found = 0;

	/* try reimporting from file */
	newmodule = PyImport_ReloadModule(module);
	if (newmodule)
		return newmodule;

	/* no file, try importing from memory */
	PyErr_Fetch(&exception, &err, &tb); /*restore for probable later use */

	newmodule = bpy_text_reimport(module, &found);
	if (newmodule) { /* found module as blender text, ignore above exception */
		PyErr_Clear();
		Py_XDECREF(exception);
		Py_XDECREF(err);
		Py_XDECREF(tb);
		/* printf("imported from text buffer...\n"); */
	}
	else if (found == 1) { /* blender text module failed to execute but was found, use its error message */
		Py_XDECREF(exception);
		Py_XDECREF(err);
		Py_XDECREF(tb);
		return NULL;
	}
	else {
		/* no blender text was found that could import the module
		 * reuse the original error from PyImport_ImportModuleEx */
		PyErr_Restore(exception, err, tb);
	}

	return newmodule;
}
Esempio n. 17
0
bool SCA_PythonController::Import()
{
	m_bModified= false;

	/* in case we re-import */
	Py_XDECREF(m_function);
	m_function= NULL;
	
	std::string mod_path = m_scriptText; /* just for storage, use C style string access */
	std::string function_string;

	const int pos = mod_path.rfind('.');
	if (pos != std::string::npos) {
		function_string = mod_path.substr(pos + 1);
		mod_path = mod_path.substr(0, pos);
	}

	if (function_string.empty()) {
		CM_LogicBrickError(this, "python module name formatting expected 'SomeModule.Func', got '" << m_scriptText << "'");
		return false;
	}

	// Import the module and print an error if it's not found
	PyObject *mod = PyImport_ImportModule(mod_path.c_str());

	if (mod == NULL) {
		ErrorPrint("Python module can't be imported");
		return false;
	}

	if (m_debug)
		mod = PyImport_ReloadModule(mod);

	if (mod == NULL) {
		ErrorPrint("Python module can't be reloaded");
		return false;
	}

	// Get the function object
	m_function = PyObject_GetAttrString(mod, function_string.c_str());

	// DECREF the module as we don't need it anymore
	Py_DECREF(mod);

	if (m_function==NULL) {
		if (PyErr_Occurred())
			ErrorPrint("python controller found the module but could not access the function");
		else
			CM_LogicBrickError(this, "python module '" << m_scriptText << "' found but function missing");
		return false;
	}
	
	if (!PyCallable_Check(m_function)) {
		Py_DECREF(m_function);
		m_function = NULL;
		CM_LogicBrickError(this, "python module function '" << m_scriptText << "' not callable");
		return false;
	}
	
	m_function_argc = 0; /* rare cases this could be a function that isn't defined in python, assume zero args */
	if (PyFunction_Check(m_function)) {
		m_function_argc= ((PyCodeObject *)PyFunction_GET_CODE(m_function))->co_argcount;
	}
	
	if (m_function_argc > 1) {
		Py_DECREF(m_function);
		m_function = NULL;
		CM_LogicBrickError(this, "python module function:\n '" << m_scriptText << "' takes " << m_function_argc
		<< " args, should be zero or 1 controller arg");
		return false;
	}
	
	return true;
}
Esempio n. 18
0
bool SCA_PythonController::Import()
{
	//printf("py module modified '%s'\n", m_scriptName.Ptr());
	m_bModified= false;

	/* incase we re-import */
	Py_XDECREF(m_function);
	m_function= NULL;
	
	STR_String mod_path_str= m_scriptText; /* just for storage, use C style string access */
	char *mod_path= mod_path_str.Ptr();
	char *function_string;

	function_string= strrchr(mod_path, '.');

	if(function_string == NULL) {
		printf("Python module name formatting error \"%s\":\n\texpected \"SomeModule.Func\", got \"%s\"\n", GetName().Ptr(), m_scriptText.Ptr());
		return false;
	}

	*function_string= '\0';
	function_string++;

	// Import the module and print an error if it's not found
	PyObject *mod = PyImport_ImportModule(mod_path);

	if (mod == NULL) {
		ErrorPrint("Python module can't be imported");
		return false;
	}

	if(m_debug)
		mod = PyImport_ReloadModule(mod);

	if (mod == NULL) {
		ErrorPrint("Python module can't be reloaded");
		return false;
	}

	// Get the function object
	m_function = PyObject_GetAttrString(mod, function_string);

	// DECREF the module as we don't need it anymore
	Py_DECREF(mod);

	if(m_function==NULL) {
		if(PyErr_Occurred())
			ErrorPrint("Python controller found the module but could not access the function");
		else
			printf("Python module error \"%s\":\n \"%s\" module found but function missing\n", GetName().Ptr(), m_scriptText.Ptr());
		return false;
	}
	
	if(!PyCallable_Check(m_function)) {
		Py_DECREF(m_function);
		printf("Python module function error \"%s\":\n \"%s\" not callable\n", GetName().Ptr(), m_scriptText.Ptr());
		return false;
	}
	
	m_function_argc = 0; /* rare cases this could be a function that isnt defined in python, assume zero args */
	if (PyFunction_Check(m_function)) {
		PyObject *py_arg_count = PyObject_GetAttrString(PyFunction_GET_CODE(m_function), "co_argcount");
		if(py_arg_count) {
			m_function_argc = PyLong_AsLong(py_arg_count);
			Py_DECREF(py_arg_count);
		}
		else {
			PyErr_Clear(); /* unlikely to fail but just incase */
		}
	}
	
	if(m_function_argc > 1) {
		Py_DECREF(m_function);
		printf("Python module function has \"%s\":\n \"%s\" takes %d args, should be zero or 1 controller arg\n", GetName().Ptr(), m_scriptText.Ptr(), m_function_argc);
		return false;
	}
	
	return true;
}
Esempio n. 19
0
PyObject *PythonModules::loadModule(QString modulePath, bool reload, bool *firstLoad)
{
    PyObject *pModule = nullptr;
    if (modulePath.isEmpty()) { // should have been checked earlier already, but who knows ...
        callback->logError(tr("Empty module path name, nothing to load..."));
        return pModule;
    }

    PyGILState_STATE lgstate;
    lgstate = PyGILState_Ensure();

    if (!modulesPath.contains(modulePath)) {
        qDebug() << "Instanciating the module for the first time " << modulePath;
        QString moduleName = getModuleNameFromFile(modulePath);
        if (!checkModuleNameAndPath(modulePath, moduleName)) { // checking if the module is already there from another file
            PyGILState_Release(lgstate);
            return pModule;
        }
        pModule = PyImport_ImportModule(moduleName.toUtf8().data()); // new reference
        if (!checkPyError()) {
            callback->logError(tr("Module \"%1\" could not be loaded:\n %2").arg(modulePath).arg(errorMessage));
            pModule = nullptr;
        } else {
            if (!checkModuleNameAndPath(modulePath, moduleName)) { // checking if the module loaded comes from the file that was supplied
                Py_XDECREF(pModule);
                pModule = nullptr;
                PyGILState_Release(lgstate);
                return pModule;
            }

            if (PyObject_HasAttrString(pModule, MAIN_FUNCTION_NAME) != 1) {
                callback->logError(tr("The python module %2 does not have the %1 method").arg(QString::fromUtf8(MAIN_FUNCTION_NAME)).arg(moduleName));
                Py_XDECREF(pModule);
                pModule = nullptr;
                PyGILState_Release(lgstate);
                return pModule;
            } else {
                modulesPath.insert(modulePath,pModule);
                if (firstLoad != nullptr)
                    *firstLoad = true;
            }
        }

    } else if (reload) {
        qDebug() << "Reloading module" << modulePath;
        PyObject *oldModule = modulesPath.take(modulePath); // the module object is either going to be replaced or cleared
        // clearing global objects (we don't care about any error message here)
        PyObject * attr = PyObject_GetAttrString(oldModule,INBOUND_ATTR_NAME);
        PyErr_Clear();
        Py_XDECREF(attr);
        attr = PyObject_GetAttrString(oldModule,ISTWOWAY_ATTR_NAME);
        PyErr_Clear();
        Py_XDECREF(attr);
        attr = PyObject_GetAttrString(oldModule,PARAMS_ATTR_NAME);
        PyErr_Clear();
        Py_XDECREF(attr);
        attr = PyObject_GetAttrString(oldModule,PARAMS_NAMES_ATTR_NAME);
        PyErr_Clear();
        Py_XDECREF(attr);

        // reloading
        pModule = PyImport_ReloadModule(oldModule); // new ref ??
        if (pModule != oldModule) {
            Py_XDECREF(oldModule); // clearing the old module object if the new ref is different
        }

        if (!checkPyError()) {
            callback->logError(tr("Error(s) while reloading the module %1, removing it from the the registered modules.\n%2").arg(modulePath).arg(errorMessage));
            pModule = nullptr;
        } else {
            modulesPath.insert(modulePath,pModule);
        }

    } else {
        qDebug() << "no reload, taking the module as it is already" << modulePath;
        pModule = modulesPath.value(modulePath);
    }

    PyGILState_Release(lgstate);
    return pModule;
}
Esempio n. 20
0
static void eval_some_python(const char *funcname, char *args, switch_core_session_t *session, switch_stream_handle_t *stream, switch_event_t *params,
							 char **str, struct switch_py_thread *pt)
{
	PyThreadState *tstate = NULL;
	char *dupargs = NULL;
	char *argv[2] = { 0 };
	int argc;
	char *script = NULL;
	PyObject *module = NULL, *sp = NULL, *stp = NULL, *eve = NULL;
	PyObject *function = NULL;
	PyObject *arg = NULL;
	PyObject *result = NULL;
	char *p;

	if (str) {
		*str = NULL;
	}

	if (args) {
		dupargs = strdup(args);
	} else {
		return;
	}

	assert(dupargs != NULL);

	if (!(argc = switch_separate_string(dupargs, ' ', argv, (sizeof(argv) / sizeof(argv[0]))))) {
		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "No module name specified!\n");
		goto done;
	}

	script = strdup(switch_str_nil(argv[0]));

	if ((p = strstr(script, "::"))) {
		*p = '\0';
		p += 2;
		if (p) {
			funcname = p;
		}
	}

	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_NOTICE, "Invoking py module: %s\n", script);

	tstate = PyThreadState_New(mainThreadState->interp);
	if (!tstate) {
		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "error acquiring tstate\n");
		goto done;
	}

	/* Save state in thread struct so we can terminate it later if needed */
	if (pt)
		pt->tstate = tstate;

	// swap in thread state
	PyEval_AcquireThread(tstate);
	init_freeswitch();

	// import the module
	module = PyImport_ImportModule((char *) script);
	if (!module) {
		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Error importing module\n");
		PyErr_Print();
		PyErr_Clear();
		goto done_swap_out;
	}
	// reload the module
	module = PyImport_ReloadModule(module);
	if (!module) {
		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Error reloading module\n");
		PyErr_Print();
		PyErr_Clear();
		goto done_swap_out;
	}
	// get the handler function to be called
	function = PyObject_GetAttrString(module, (char *) funcname);
	if (!function) {
		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Module does not define %s\n", funcname);
		PyErr_Print();
		PyErr_Clear();
		goto done_swap_out;
	}

	if (session) {
		sp = mod_python_conjure_session(module, session);
	}

	if (params) {
		eve = mod_python_conjure_event(params);
	}

	if (stream) {
		stp = mod_python_conjure_stream(stream);
		if (stream->param_event) {
			eve = mod_python_conjure_event(stream->param_event);
		}
	}

	if (sp && eve && stp) {
		arg = Py_BuildValue("(OOOs)", sp, stp, eve, switch_str_nil(argv[1]));
	} else if (eve && stp) {
		arg = Py_BuildValue("(sOOs)", "na", stp, eve, switch_str_nil(argv[1]));
	} else if (eve) {
		arg = Py_BuildValue("(Os)", eve, switch_str_nil(argv[1]));
	} else if (sp) {
		arg = Py_BuildValue("(Os)", sp, switch_str_nil(argv[1]));
	} else {
		arg = Py_BuildValue("(s)", switch_str_nil(argv[1]));
	}

	// invoke the handler 
	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Call python script \n");
	result = PyEval_CallObjectWithKeywords(function, arg, (PyObject *) NULL);
	Py_DECREF(function);
	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Finished calling python script \n");

	// check the result and print out any errors
	if (result) {
		if (str) {
			*str = strdup((char *) PyString_AsString(result));
		}
	} else if (!PyErr_ExceptionMatches(PyExc_SystemExit)) {
		// Print error, but ignore SystemExit 
		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Error calling python script\n");
		PyErr_Print();
		PyErr_Clear();
		PyRun_SimpleString("python_makes_sense");
		PyGC_Collect();
	}

  done_swap_out:

	if (arg) {
		Py_DECREF(arg);
	}

	if (sp) {
		Py_DECREF(sp);
	}

	if (tstate) {
		// thread state must be cleared explicitly or we'll get memory leaks
		PyThreadState_Clear(tstate);
		PyEval_ReleaseThread(tstate);
		PyThreadState_Delete(tstate);
	}

  done:

	switch_safe_free(dupargs);
	switch_safe_free(script);


}