Exemplo n.º 1
0
void init_uwsgi_embedded_module() {
	PyObject *new_uwsgi_module, *zero;
	int i;

	PyType_Ready(&uwsgi_InputType);

	/* initialize for stats */
	up.workers_tuple = PyTuple_New(uwsgi.numproc);
	for (i = 0; i < uwsgi.numproc; i++) {
		zero = PyDict_New();
		Py_INCREF(zero);
		PyTuple_SetItem(up.workers_tuple, i, zero);
	}


#ifdef PYTHREE
	PyImport_AppendInittab("uwsgi", init_uwsgi3);
	new_uwsgi_module = PyImport_AddModule("uwsgi");
#else
	new_uwsgi_module = Py_InitModule3("uwsgi", NULL, uwsgi_py_doc);
#endif
	if (new_uwsgi_module == NULL) {
		uwsgi_log("could not initialize the uwsgi python module\n");
		exit(1);
	}



	Py_INCREF((PyObject *) &uwsgi_InputType);

	up.embedded_dict = PyModule_GetDict(new_uwsgi_module);
	if (!up.embedded_dict) {
		uwsgi_log("could not get uwsgi module __dict__\n");
		exit(1);
	}

	// just for safety
	Py_INCREF(up.embedded_dict);


	if (PyDict_SetItemString(up.embedded_dict, "version", PyString_FromString(UWSGI_VERSION))) {
		PyErr_Print();
		exit(1);
	}

	PyObject *uwsgi_py_version_info = PyTuple_New(5);

	PyTuple_SetItem(uwsgi_py_version_info, 0, PyInt_FromLong(UWSGI_VERSION_BASE));
	PyTuple_SetItem(uwsgi_py_version_info, 1, PyInt_FromLong(UWSGI_VERSION_MAJOR));
	PyTuple_SetItem(uwsgi_py_version_info, 2, PyInt_FromLong(UWSGI_VERSION_MINOR));
	PyTuple_SetItem(uwsgi_py_version_info, 3, PyInt_FromLong(UWSGI_VERSION_REVISION));
	PyTuple_SetItem(uwsgi_py_version_info, 4, PyString_FromString(UWSGI_VERSION_CUSTOM));

	if (PyDict_SetItemString(up.embedded_dict, "version_info", uwsgi_py_version_info)) {
		PyErr_Print();
		exit(1);
	}



	if (PyDict_SetItemString(up.embedded_dict, "hostname", PyString_FromStringAndSize(uwsgi.hostname, uwsgi.hostname_len))) {
		PyErr_Print();
		exit(1);
	}

	if (uwsgi.mode) {
		if (PyDict_SetItemString(up.embedded_dict, "mode", PyString_FromString(uwsgi.mode))) {
			PyErr_Print();
			exit(1);
		}
	}

	if (uwsgi.pidfile) {
		if (PyDict_SetItemString(up.embedded_dict, "pidfile", PyString_FromString(uwsgi.pidfile))) {
			PyErr_Print();
			exit(1);
		}
	}

#ifdef UWSGI_SPOOLER
	if (uwsgi.spoolers) {
		int sc = 0;
		struct uwsgi_spooler *uspool = uwsgi.spoolers;
		while(uspool) { sc++; uspool = uspool->next;}

		PyObject *py_spooler_tuple = PyTuple_New(sc);

		uspool = uwsgi.spoolers;
		sc = 0;

		while(uspool) {
			PyTuple_SetItem(py_spooler_tuple, sc, PyString_FromString(uspool->dir));
			sc++;
			uspool = uspool->next;
		}

		if (PyDict_SetItemString(up.embedded_dict, "spoolers", py_spooler_tuple)) {
                	PyErr_Print();
                	exit(1);
        	}
	}
#endif



	if (PyDict_SetItemString(up.embedded_dict, "SPOOL_RETRY", PyInt_FromLong(-1))) {
		PyErr_Print();
		exit(1);
	}

	if (PyDict_SetItemString(up.embedded_dict, "SPOOL_OK", PyInt_FromLong(-2))) {
		PyErr_Print();
		exit(1);
	}

	if (PyDict_SetItemString(up.embedded_dict, "SPOOL_IGNORE", PyInt_FromLong(0))) {
		PyErr_Print();
		exit(1);
	}

	if (PyDict_SetItemString(up.embedded_dict, "numproc", PyInt_FromLong(uwsgi.numproc))) {
		PyErr_Print();
		exit(1);
	}

	if (PyDict_SetItemString(up.embedded_dict, "has_threads", PyInt_FromLong(uwsgi.has_threads))) {
		PyErr_Print();
		exit(1);
	}

	if (PyDict_SetItemString(up.embedded_dict, "cores", PyInt_FromLong(uwsgi.cores))) {
		PyErr_Print();
		exit(1);
	}

	if (uwsgi.loop) {
		if (PyDict_SetItemString(up.embedded_dict, "loop", PyString_FromString(uwsgi.loop))) {
			PyErr_Print();
			exit(1);
		}
	}
	else {
		PyDict_SetItemString(up.embedded_dict, "loop", Py_None);
	}

	PyObject *py_opt_dict = PyDict_New();
	for (i = 0; i < uwsgi.exported_opts_cnt; i++) {
		if (PyDict_Contains(py_opt_dict, PyString_FromString(uwsgi.exported_opts[i]->key))) {
			PyObject *py_opt_item = PyDict_GetItemString(py_opt_dict, uwsgi.exported_opts[i]->key);
			if (PyList_Check(py_opt_item)) {
				if (uwsgi.exported_opts[i]->value == NULL) {
					PyList_Append(py_opt_item, Py_True);
				}
				else {
					PyList_Append(py_opt_item, PyString_FromString(uwsgi.exported_opts[i]->value));
				}
			}
			else {
				PyObject *py_opt_list = PyList_New(0);
				PyList_Append(py_opt_list, py_opt_item);
				if (uwsgi.exported_opts[i]->value == NULL) {
					PyList_Append(py_opt_list, Py_True);
				}
				else {
					PyList_Append(py_opt_list, PyString_FromString(uwsgi.exported_opts[i]->value));
				}

				PyDict_SetItemString(py_opt_dict, uwsgi.exported_opts[i]->key, py_opt_list);
			}
		}
		else {
			if (uwsgi.exported_opts[i]->value == NULL) {
				PyDict_SetItemString(py_opt_dict, uwsgi.exported_opts[i]->key, Py_True);
			}
			else {
				PyDict_SetItemString(py_opt_dict, uwsgi.exported_opts[i]->key, PyString_FromString(uwsgi.exported_opts[i]->value));
			}
		}
	}

	if (PyDict_SetItemString(up.embedded_dict, "opt", py_opt_dict)) {
		PyErr_Print();
		exit(1);
	}

	PyObject *py_magic_table = PyDict_New();
	uint8_t mtk;
	for (i = 0; i <= 0xff; i++) {
		// a bit of magic :P
		mtk = i;
                if (uwsgi.magic_table[i]) {
			if (uwsgi.magic_table[i][0] != 0) {
				PyDict_SetItem(py_magic_table, PyString_FromStringAndSize((char *) &mtk, 1), PyString_FromString(uwsgi.magic_table[i]));
			}
		}
        }

	if (PyDict_SetItemString(up.embedded_dict, "magic_table", py_magic_table)) {
		PyErr_Print();
		exit(1);
	}

#ifdef UNBIT
	if (PyDict_SetItemString(up.embedded_dict, "unbit", Py_True)) {
#else
	if (PyDict_SetItemString(up.embedded_dict, "unbit", Py_None)) {
#endif
		PyErr_Print();
		exit(1);
	}

	if (PyDict_SetItemString(up.embedded_dict, "buffer_size", PyInt_FromLong(uwsgi.buffer_size))) {
		PyErr_Print();
		exit(1);
	}

	if (PyDict_SetItemString(up.embedded_dict, "started_on", PyInt_FromLong(uwsgi.start_tv.tv_sec))) {
		PyErr_Print();
		exit(1);
	}

	if (PyDict_SetItemString(up.embedded_dict, "start_response", up.wsgi_spitout)) {
		PyErr_Print();
		exit(1);
	}


	if (PyDict_SetItemString(up.embedded_dict, "applications", Py_None)) {
		PyErr_Print();
		exit(1);
	}

	if (uwsgi.is_a_reload) {
		if (PyDict_SetItemString(up.embedded_dict, "is_a_reload", Py_True)) {
			PyErr_Print();
			exit(1);
		}
	}
	else {
		if (PyDict_SetItemString(up.embedded_dict, "is_a_reload", Py_False)) {
			PyErr_Print();
			exit(1);
		}
	}

	up.embedded_args = PyTuple_New(2);
	if (!up.embedded_args) {
		PyErr_Print();
		exit(1);
	}

	if (PyDict_SetItemString(up.embedded_dict, "message_manager_marshal", Py_None)) {
		PyErr_Print();
		exit(1);
	}

	init_uwsgi_module_advanced(new_uwsgi_module);

#ifdef UWSGI_SPOOLER
	if (uwsgi.spoolers) {
		init_uwsgi_module_spooler(new_uwsgi_module);
	}
#endif


	if (uwsgi.sharedareasize > 0 && uwsgi.sharedarea) {
		init_uwsgi_module_sharedarea(new_uwsgi_module);
	}

	if (uwsgi.cache_max_items > 0) {
		init_uwsgi_module_cache(new_uwsgi_module);
	}

	if (uwsgi.queue_size > 0) {
		init_uwsgi_module_queue(new_uwsgi_module);
	}

#ifdef UWSGI_SNMP
	if (uwsgi.snmp) {
		init_uwsgi_module_snmp(new_uwsgi_module);
	}
#endif

	if (up.extension) {
		up.extension();
	}
}
#endif



int uwsgi_python_magic(char *mountpoint, char *lazy) {

	char *qc = strchr(lazy, ':');
	if (qc) {
		qc[0] = 0;
		up.callable = qc + 1;
	}

	if (!strcmp(lazy + strlen(lazy) - 3, ".py")) {
		up.file_config = lazy;
		return 1;
	}
	else if (!strcmp(lazy + strlen(lazy) - 5, ".wsgi")) {
		up.file_config = lazy;
		return 1;
	}
	else if (qc && strchr(lazy, '.')) {
		up.wsgi_config = lazy;
		return 1;
	}

	// reset lazy
	if (qc) {
		qc[0] = ':';
	}
	return 0;

}
Exemplo n.º 2
0
int
main(int argc, char *argv[])
{
    PyObject *pName, *pModule, *pDict, *pFunc;
    PyObject *pArgs, *pValue;
    int i;

    if (argc < 3) {
        fprintf(stderr,"Usage: call pythonfile funcname [args]\n");
        return 1;
    }

    Py_Initialize();
    pName = PyString_FromString(argv[1]);
    /* Error checking of pName left out */

    pModule = PyImport_Import(pName);
    Py_DECREF(pName);

    if (pModule != NULL) {
        pFunc = PyObject_GetAttrString(pModule, argv[2]);
        /* pFunc is a new reference */

        if (pFunc && PyCallable_Check(pFunc)) {
            pArgs = PyTuple_New(argc - 3);
            for (i = 0; i < argc - 3; ++i) {
                pValue = PyInt_FromLong(atoi(argv[i + 3]));
                if (!pValue) {
                    Py_DECREF(pArgs);
                    Py_DECREF(pModule);
                    fprintf(stderr, "Cannot convert argument\n");
                    return 1;
                }
                /* pValue reference stolen here: */
                PyTuple_SetItem(pArgs, i, pValue);
            }
            pValue = PyObject_CallObject(pFunc, pArgs);
            Py_DECREF(pArgs);
            if (pValue != NULL) {
                printf("Result of call: %ld\n", PyInt_AsLong(pValue));
                Py_DECREF(pValue);
            }
            else {
                Py_DECREF(pFunc);
                Py_DECREF(pModule);
                PyErr_Print();
                fprintf(stderr,"Call failed\n");
                return 1;
            }
        }
        else {
            if (PyErr_Occurred())
                PyErr_Print();
            fprintf(stderr, "Cannot find function \"%s\"\n", argv[2]);
        }
        Py_XDECREF(pFunc);
        Py_DECREF(pModule);
    }
    else {
        PyErr_Print();
        fprintf(stderr, "Failed to load \"%s\"\n", argv[1]);
        return 1;
    }
    Py_Finalize();
    return 0;
}
Exemplo n.º 3
0
int assimilate_handler(WORKUNIT& wu, std::vector<RESULT>& results, RESULT& canonical_result)
{
  PyObject *retval;

  initialize_python();
#if 0// OLD
  retval = py_user_code_on_workunit(results, &canonical_result, "assimilators");
  if(retval == NULL)
    {
      fprintf(stderr,"[%s:%d] There was a python error when assimilating %s.\nExiting.\n",__FILE__,__LINE__,canonical_result.name);
      finalize_python();
      exit(1);
    }
  Py_DECREF(retval);

  if(PyErr_Occurred())
    {
      printf("Assimilation failed\n");
      PyErr_Print();
      finalize_python();
      return 1;
    }
#else // New
    std::string command;
  
  if(PyRun_SimpleString("import boinctools;results = []"))
    {
      fprintf(stderr,"Could not import boinctools python module.\n");
      if(PyErr_Occurred())
	PyErr_Print();
      finalize_python();
      exit(1);
    }
  
  // Create Result Class
  command = "canonical = " + result_init_string(canonical_result);
  if(PyRun_SimpleString(command.c_str()))
    {
      fprintf(stderr,"Could not create result object.\n");
      fprintf(stderr,"Python command: %s",command.c_str());
      if(PyErr_Occurred())
	PyErr_Print();
      finalize_python();
      exit(1);
    }

  for(std::vector<RESULT>::const_iterator result = results.begin();result != results.end();result++)
    {
      command = "results.append(" + result_init_string(*result) + ")";
      if(PyRun_SimpleString(command.c_str()))
	{
	  fprintf(stderr,"Could not add result object to assimilation result list.\n");
	  fprintf(stderr,"Python command: %s",command.c_str());
	  if(PyErr_Occurred())
	    PyErr_Print();
	  finalize_python();
	  exit(1);
	}
    }
  
  command = "boinctools.assimilator(results,canonical)";
  if(PyRun_SimpleString(command.c_str()))
    {
      fprintf(stderr,"Could not assimilate result objects.\n");
      fprintf(stderr,"Python command: %s",command.c_str());
      if(PyErr_Occurred())
	PyErr_Print();
      finalize_python();
      exit(1);
    }
  
#endif
  return 0;


}
Exemplo n.º 4
0
void PythonScriptInterface::HandleEvent(int event_id, void *user, void *extra) {
	ClientInfoTable *tbl = findClient(user, true);
	mp_current_info_table = tbl;
	PyObject* sys_mod_dict = PyImport_GetModuleDict();
	PyObject* main_mod = PyMapping_GetItemString(sys_mod_dict, "__main__");
	switch(event_id) {
		case CHCGS_ClientConnectEvent: {
			tbl->connection_object = PyObject_CallMethod(main_mod, mp_connection_handler->tp_name, "");
			PyErr_Print();
			printf("Client connect %p | %p (%s)\n", tbl->connection_object, mp_connection_handler, mp_connection_handler->tp_name);
			break;
		}
		case CHCGS_ClientDisconnectEvent: {
			Py_XDECREF(tbl->connection_object);
			printf("Client disconnect\n");
			break;
		}
		case CHCGS_EnterWorld: {
			if(tbl->entity)
				PyObject_CallMethod(tbl->entity, "OnEnterWorld", "");
			break;
		}
		case CHCGS_ClientCommand: {
			HandleClientCommand(user, (const char *)extra);
			break;
		}
		case CHCGS_DialogResponse: {
			DialogEvent *devent = (DialogEvent *)extra;
			if(tbl->last_dialog_callback) {
				PyObject *arglist = Py_BuildValue("iis",(int)devent->list_index, (int)devent->button_id,devent->input);
				PyObject *ret = PyObject_CallObject(tbl->last_dialog_callback, arglist);
				Py_DECREF(tbl->last_dialog_callback);
				tbl->last_dialog_callback = NULL;
				PyErr_Print();
				Py_XDECREF(arglist);
				Py_XDECREF(ret);
			}
			break;
		}
		case CHCGS_SpawnSelect: {
			if(tbl->entity) {
				PyObject_CallMethod(tbl->connection_object, "OnSpawnSelect", "i", extra);
			}
			break;
		}
		case CHCGS_ChatMessage: {
			PyObject_CallMethod(tbl->connection_object, "OnChatMessage", "s", extra);
			break;
		}
		case CHCGS_UIClick: {
			if(tbl->mouse_callback) {
				PyObject *arglist;
				if(extra == (void *)-1) {
					arglist = Py_BuildValue("Os", tbl->connection_object, NULL);
				} else {
					arglist = Py_BuildValue("Oi", tbl->connection_object,extra);
				}
				PyObject *ret = PyObject_CallObject(tbl->mouse_callback, arglist);
				PyErr_Print();
				Py_XDECREF(arglist);
				Py_XDECREF(ret);
			}
			break;
		}
		case CHCGS_PlayerDeath: {
			SAMPDeathInfo *death_info = (SAMPDeathInfo *)extra;
			SAMPDriver *driver = this->getGameServer()->getSAMPDriver();
			printf("Send death: %d  %d\n", ((SAMPPlayer *)user)->GetPlayerID(), death_info->killer_id);
			driver->BroadcastDeath((SAMPPlayer *)user, (SAMPPlayer *)driver->findPlayerByID(death_info->killer_id), 0);
			break;
		}
	}
}
Exemplo n.º 5
0
ZenController *zen_controller_new(const char *zendir, const char *profiles_dir)
{
	ZenController *result;
	char zen_path[PATH_MAX + 20] = { 0 };
	PyObject *module, *cls;

	result = malloc(sizeof(ZenController));
	result->editor = NULL;
	result->run_action = NULL;
	result->set_context = NULL;
	result->set_active_profile = NULL;

	zen_controller_init_python();

	PyRun_SimpleString("import sys");
	snprintf(zen_path, PATH_MAX + 20 - 1, "sys.path.append('%s')", zendir);
	PyRun_SimpleString(zen_path);

	module = PyImport_ImportModule("zencoding");
	if (module == NULL)
	{
		if (PyErr_Occurred())
			PyErr_Print();
		free(result);
		return NULL;
	}

	/*
	 * For some reason on Python 2.7.0+ "pre-importing" these prevents a
	 * segfault below in zen_controller_run_action() where it calls the
	 * Zen Coding run_action() function.
	 *
	 * I would *LOVE* to know what's going on, I've spent far too long trying
	 * to debug this :)
	 */
	PyRun_SimpleString("import zencoding.actions");
	PyRun_SimpleString("import zencoding.filters");
	PyRun_SimpleString("import zencoding.utils");

	result->run_action = PyObject_GetAttrString(module, "run_action");
	if (result->run_action == NULL)
	{
		if (PyErr_Occurred())
			PyErr_Print();
		Py_XDECREF(module);
		free(result);
		return NULL;
	}

	if (!PyCallable_Check(result->run_action))
	{
		Py_XDECREF(result->run_action);
		Py_XDECREF(module);
		free(result);
		return NULL;
	}

	Py_XDECREF(module);


	module = zen_editor_module_init();
	if (module == NULL)
	{
		if (PyErr_Occurred())
			PyErr_Print();
		Py_XDECREF(result->run_action);
		free(result);
		return NULL;
	}

	cls = PyObject_GetAttrString(module, "ZenEditor");
	if (cls == NULL)
	{
		if (PyErr_Occurred())
			PyErr_Print();
		Py_XDECREF(module);
		Py_XDECREF(result->run_action);
		free(result);
		return NULL;
	}
	Py_XDECREF(module);

	result->editor = PyObject_CallObject(cls, NULL);
	if (result->editor == NULL)
	{
		if (PyErr_Occurred())
			PyErr_Print();
		Py_XDECREF(cls);
		Py_XDECREF(result->run_action);
		free(result);
		return NULL;
	}

	Py_XDECREF(cls);

	result->set_context = PyObject_GetAttrString(result->editor, "set_context");
	if (result->set_context == NULL)
	{
		if (PyErr_Occurred())
			PyErr_Print();
		Py_XDECREF(result->editor);
		Py_XDECREF(result->run_action);
		free(result);
		return NULL;
	}
	else if (!PyCallable_Check(result->set_context))
	{
		Py_XDECREF(result->editor);
		Py_XDECREF(result->run_action);
		Py_XDECREF(result->set_context);
		free(result);
		return NULL;
	}

	result->set_active_profile = PyObject_GetAttrString(result->editor, "set_profile_name");
	if (result->set_active_profile == NULL)
	{
		if (PyErr_Occurred())
			PyErr_Print();
		Py_XDECREF(result->editor);
		Py_XDECREF(result->run_action);
		Py_XDECREF(result->set_context);
		free(result);
		return NULL;
	}
	else if (!PyCallable_Check(result->set_active_profile))
	{
		Py_XDECREF(result->editor);
		Py_XDECREF(result->run_action);
		Py_XDECREF(result->set_context);
		Py_XDECREF(result->set_active_profile);
		free(result);
		return NULL;
	}

	/* Initialize/setup profiles */
	PyObject *res;
	res = PyObject_CallMethod(result->editor, "init_profiles", "(s)", profiles_dir);
	if (res == NULL)
	{
		if (PyErr_Occurred())
			PyErr_Print();
		g_warning("Unable to initialize profiles");
	}
	else
		Py_XDECREF(res);

	return result;
}
Exemplo n.º 6
0
Bool eval_intermediate_callback(Index alg_mod,	/* 0 is regular, 1 is resto */
				Index iter_count, Number obj_value,
				Number inf_pr, Number inf_du,
				Number mu, Number d_norm,
				Number regularization_size,
				Number alpha_du, Number alpha_pr,
				Index ls_trials, UserDataPtr data)
{
	logger("[Callback:E]intermediate_callback");

	DispatchData *myowndata = (DispatchData *) data;
	UserDataPtr user_data = (UserDataPtr) myowndata->userdata;

	long result_as_long;
	Bool result_as_bool;

	PyObject *python_algmod = Py_BuildValue("i", alg_mod);
	PyObject *python_iter_count = Py_BuildValue("i", iter_count);
	PyObject *python_obj_value = Py_BuildValue("d", obj_value);
	PyObject *python_inf_pr = Py_BuildValue("d", inf_pr);
	PyObject *python_inf_du = Py_BuildValue("d", inf_du);
	PyObject *python_mu = Py_BuildValue("d", mu);
	PyObject *python_d_norm = Py_BuildValue("d", d_norm);
	PyObject *python_regularization_size =
	    Py_BuildValue("d", regularization_size);
	PyObject *python_alpha_du = Py_BuildValue("d", alpha_du);
	PyObject *python_alpha_pr = Py_BuildValue("d", alpha_pr);
	PyObject *python_ls_trials = Py_BuildValue("i", ls_trials);

	PyObject *arglist = NULL;

	if (user_data != NULL)
		arglist = Py_BuildValue("(OOOOOOOOOOOO)",
					python_algmod,
					python_iter_count,
					python_obj_value,
					python_inf_pr,
					python_inf_du,
					python_mu,
					python_d_norm,
					python_regularization_size,
					python_alpha_du,
					python_alpha_pr,
					python_ls_trials,
					(PyObject *) user_data);
	else
		arglist = Py_BuildValue("(OOOOOOOOOOO)",
					python_algmod,
					python_iter_count,
					python_obj_value,
					python_inf_pr,
					python_inf_du,
					python_mu,
					python_d_norm,
					python_regularization_size,
					python_alpha_du,
					python_alpha_pr, python_ls_trials);

	PyObject *result =
	    PyObject_CallObject(myowndata->eval_intermediate_callback_python,
				arglist);

	if (!result)
		PyErr_Print();

	result_as_long = PyInt_AsLong(result);
	result_as_bool = (Bool) result_as_long;

	Py_DECREF(result);
	Py_CLEAR(arglist);
	logger("[Callback:R] intermediate_callback");
	return result_as_bool;
}
Exemplo n.º 7
0
void XBPyThread::Process()
{
  CLog::Log(LOGDEBUG,"Python thread: start processing");

  char path[1024];
  char sourcedir[1024];

  // get the global lock
  PyEval_AcquireLock();

  m_threadState = Py_NewInterpreter();
  PyEval_ReleaseLock();

  if (!m_threadState) {
	CLog::Log(LOGERROR,"Python thread: FAILED to get thread state!");
	return;
  }

  PyEval_AcquireLock();

  // swap in my thread state
  PyThreadState_Swap(m_threadState);

  m_pExecuter->InitializeInterpreter();

  // get path from script file name and add python path's
  // this is used for python so it will search modules from script path first
  strcpy(sourcedir, source);
  
#ifndef _LINUX
  strcpy(strrchr(sourcedir, PATH_SEPARATOR_CHAR), ";");
#else
  strcpy(strrchr(sourcedir, PATH_SEPARATOR_CHAR), ":");
#endif

  strcpy(path, sourcedir);

#ifndef _LINUX
  strcat(path, dll_getenv("PYTHONPATH"));
#else
#ifdef __APPLE__
  strcat(path, _P("Q:\\system\\python\\python24.zlib:"));
  strcat(path, _P("Q:\\system\\python\\lib-osx"));
#else
  strcat(path, Py_GetPath());
#endif
#endif

  // set current directory and python's path.
  if (argv != NULL)
  {
    PySys_SetArgv(argc, argv);
  }
  PySys_SetPath(path);

#ifdef _LINUX
  // Replace the : at the end with ; so it will be EXACTLY like the xbox version
  strcpy(strrchr(sourcedir, ':'), ";");
#endif  
  xbp_chdir(sourcedir); // XXX, there is a ';' at the end

  if (type == 'F')
  {
    // run script from file
    FILE *fp = fopen(source, "r");
    if (fp)
    {
      if (PyRun_SimpleFile(fp, source) == -1)
      {
        CLog::Log(LOGERROR, "Scriptresult: Error\n");
        if (PyErr_Occurred())	PyErr_Print();
      }
      else CLog::Log(LOGINFO, "Scriptresult: Succes\n");
      fclose(fp);
    }
    else CLog::Log(LOGERROR, "%s not found!\n", source);
  }
  else
  {
    //run script
    if (PyRun_SimpleString(source) == -1)
    {
      CLog::Log(LOGERROR, "Scriptresult: Error\n");
      if (PyErr_Occurred()) PyErr_Print();
    }
    else CLog::Log(LOGINFO, "Scriptresult: Success\n");
  }

  PyEval_ReleaseLock();

  // when a script uses threads or timers - we have to wait for them to be over before we terminate the interpreter.
  // so first - release the lock and allow the threads to terminate.
  
  ::Sleep(500);
  PyEval_AcquireLock();

  PyThreadState_Swap(m_threadState);

  // look waiting for the running threads to end
  PyRun_SimpleString(
        "import threading\n"
        "import sys\n"
        "try:\n"
            "\tthreads = list(threading.enumerate())\n"
        "except:\n"
            "\tprint 'error listing threads'\n"
        "while threading.activeCount() > 1:\n"
        "\tfor thread in threads:\n"
            "\t\tif thread <> threading.currentThread():\n"
            "\t\t\tprint 'waiting for thread - ' + thread.getName()\n"
            "\t\t\tthread.join(1000)\n"
        );

  m_pExecuter->DeInitializeInterpreter();

  Py_EndInterpreter(m_threadState);
  m_threadState = NULL;
  PyEval_ReleaseLock();
}
Exemplo n.º 8
0
Arquivo: player.c Projeto: yzzyx/adv
/* move_player
 *
 * called each tick, updating the player's position
 */
int
monster_move(PyObject *monster)
{
	int x1, y1; /* current position */
	int x2, y2; /* target position */
	int speed;
	node_t *active_path;

	/* Check if we have an active path */
	active_path = (node_t*)py_getattr_int(monster, ATTR_INT_ACTIVE_PATH);
	if (active_path == 0)
		return 0;

	x1 = py_getattr_int(monster, ATTR_X);
	y1 = py_getattr_int(monster, ATTR_Y);
	x2 = active_path->x;
	y2 = active_path->y;
	speed = py_getattr_int(monster, ATTR_INT_SPEED);

	/* monster-move-int
	 * ----------------
	 */

	int dx = 0, dy = 0;
	int sx, sy;
	int err;
	int x, y;
	int i;

	dx = abs(x2-x1);
	dy = abs(y2-y1);
	if (x1 < x2) sx = 1; else sx = -1;
	if (y1 < y2) sy = 1; else sy = -1;
	err = dx-dy;
	x = x1;
	y = y1;

	for(i = 0;i < speed; i++) {
		if (x == x2 && y == y2)
			break;

		int e2 = 2 * err;
		if (e2 > -dy) {
			err = err - dy;
			x += sx;
		}
		if (x == x2 && y == y2) {
			break;
		}
		if (e2 < dx) {
			err = err + dx;
			y += sy;
		}
	}
	py_setattr_int(monster, ATTR_X, x);
	py_setattr_int(monster, ATTR_Y, y);

	/* We've reached our target */
	if (x == x2 && y == y2) {
		active_path = active_path->child;
		py_setattr_int(monster, ATTR_INT_ACTIVE_PATH, (long)active_path);
	}
	return 0;

#if 0
	/* FIXME! Call playerExit-method on tile we're leaving*/
	tmp = PyObject_CallMethod(
		p->map->tiles[prev_tile_x + prev_tile_y * p->map->width]->py_obj,
		"playerExit", "", NULL);
	if (tmp == NULL) { PyErr_Print(); return -1; }
	Py_DECREF(tmp);

	/* FIXME! Call playerEnter-method on tile we're entering*/
	tmp = PyObject_CallMethod(p->map->tiles[p->tile_x + p->tile_y * p->map->width]->py_obj,
		"playerEnter", "", NULL);
	if (tmp == NULL) { PyErr_Print(); return -1; }
	Py_DECREF(tmp);
	p->is_dirty = 1;
#endif
}
Exemplo n.º 9
0
CompiledPythonFragment * getCompiledCode( Table * table, int pkey, const QString & pCode, const QString & codeName )
{
	CompiledPythonFragment * ret = 0;
	ensurePythonInitialized();
	// Create the key for looking up the code fragment in the cache
	QPair<Table*,int> codeKey = qMakePair(table,pkey);

	// Return the cached code fragment, if the code still matches
	if( codeCache.contains( codeKey ) ) {
		CompiledPythonFragment * frag = &codeCache[codeKey];
		// This should actually be very fast because of QString's
		// implicit sharing, should usually just be a pointer comparison
		if( frag->codeString == pCode )
			return frag;

		// Remove from cache if the fragment is out of date
		// TODO: This should free any references and remove the module
		// this isn't a big deal though, since code fragments won't
		// change very often during program execution
		codeCache.remove( codeKey );
	}

	if( pCode.isEmpty() )
		return 0;

	// Compile the code
	CompiledPythonFragment frag;
	frag.codeString = pCode;
	SIP_BLOCK_THREADS
	frag.code = (PyCodeObject*)Py_CompileString( pCode.toLatin1(), codeName.toLatin1(), Py_file_input );
	SIP_UNBLOCK_THREADS
	if( !frag.code )
	{
		PyErr_Print();
		LOG_5( "PathTemplate:getCompiledCode: Error Compiling Python code for: " + table->schema()->tableName() + " " + QString::number( pkey ) + " " + codeName );
		return 0;
	}

	// Load the code into a module
	// This is the only way i could figure out how to make the globals work properly
	// before i was using PyEval_EvalCode, passing the __main__ dict as the globals
	// but this wasn't working properly when calling the functions later, because
	// the import statements were lost.
	// This method works great and takes less code.
	
	// Generate a unique module name
	QString moduleName = "__" + table->schema()->tableName() + "__" + QString::number(pkey) + "__";
	// Returns a NEW ref
	SIP_BLOCK_THREADS
	PyObject * module = PyImport_ExecCodeModule(moduleName.toLatin1().data(),(PyObject*)frag.code);
	if( !module ) {
		PyErr_Print();
		LOG_3( "Unable to execute code module" );
	}

	// Save the modules dict, so we can lookup the function later
	else {
		frag.locals = PyModule_GetDict(module);
		Py_INCREF(frag.locals);
		codeCache[codeKey] = frag;
		ret = &codeCache[codeKey];
	}
	SIP_UNBLOCK_THREADS

	return ret;
}
Exemplo n.º 10
0
int main(int argc, char *argv[])
{
    // Use UTF-8, ignoring any LANG settings in the environment
    QTextCodec::setCodecForLocale(QTextCodec::codecForName("UTF-8"));

    {   // Set the default OpenGL version to be 2.1 with sample buffers
        QSurfaceFormat format;
        format.setVersion(2, 1);
        QSurfaceFormat::setDefaultFormat(format);
    }

    // Create the Application object
    App app(argc, argv);

    // Initialize various Python modules and the interpreter itself
    fab::preInit();
    Graph::preInit();
    AppHooks::preInit();
    Py_Initialize();

    // Set locale to C to make atof correctly parse floats
    setlocale(LC_NUMERIC, "C");

    {   // Modify Python's default search path to include the application's
        // directory (as this doesn't happen on Linux by default)
#if defined Q_OS_MAC
        QStringList path = QCoreApplication::applicationDirPath().split("/");
        path.removeLast();
        path << "Resources";
        fab::postInit({path.join("/").toStdString()});
#elif defined Q_OS_LINUX
        auto dir = QCoreApplication::applicationDirPath();
        std::vector<std::string> fab_paths =
            {(dir + "/sb").toStdString(),
             (dir + "/../share/antimony/").toStdString()};
        for (auto p : QStandardPaths::standardLocations(
                QStandardPaths::AppDataLocation))
        {
            fab_paths.push_back(p.toStdString());
        }
        fab::postInit(fab_paths);
#else
#error "Unknown OS!"
#endif
    }

    {   // Install operator.or_ as a reducer for shapes
        auto op = PyImport_ImportModule("operator");
        Datum::installReducer(fab::ShapeType, PyObject_GetAttrString(op, "or_"));
        Py_DECREF(op);
    }

    {   // Check to make sure that the fab module exists
        PyObject* fab = PyImport_ImportModule("fab");
        if (!fab)
        {
            PyErr_Print();
            QMessageBox::critical(NULL, "Import error",
                    "Import Error:<br><br>"
                    "Could not find <tt>fab</tt> Python module.<br>"
                    "Antimony will now exit.");
            exit(1);
        }
        Py_DECREF(fab);
    }

    {   // Parse command-line arguments
        QCommandLineParser parser;
        parser.setApplicationDescription("CAD from a parallel universe");
        parser.addHelpOption();
        QCommandLineOption forceHeightmap("heightmap",
                "Open 3D windows in heightmap mode");
        parser.addOption(forceHeightmap);
        parser.addPositionalArgument("file", "File to open", "[file]");

        parser.process(app);

        auto args = parser.positionalArguments();
        if (args.length() > 1)
        {
            qCritical("Too many command-line arguments");
            exit(1);
        }
        else if (args.length() == 1)
        {
            app.loadFile(args[0]);
        }
    }

    app.makeDefaultWindows();
    return app.exec();
}
Exemplo n.º 11
0
void PythonHostEnvironment::printError()
{
	PyErr_Print();
	PyErr_Clear();
}
Exemplo n.º 12
0
PyMODINIT_FUNC initnumpy_quaternion(void)
{
    PyObject *m;
    int quaternionNum;
    PyObject* numpy = PyImport_ImportModule("numpy");
    PyObject* numpy_dict = PyModule_GetDict(numpy);
    int arg_types[3];

    m = Py_InitModule("numpy_quaternion", QuaternionMethods);
    if (m == NULL) {
        return;
    }

    /* Make sure NumPy is initialized */
    import_array();
    import_umath();

    /* Register the quaternion array scalar type */
#if defined(NPY_PY3K)
    PyQuaternionArrType_Type.tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE;
#else
    PyQuaternionArrType_Type.tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_CHECKTYPES;
#endif
    PyQuaternionArrType_Type.tp_new = quaternion_arrtype_new;
    PyQuaternionArrType_Type.tp_richcompare = gentype_richcompare;
    PyQuaternionArrType_Type.tp_hash = quaternion_arrtype_hash;
    PyQuaternionArrType_Type.tp_repr = quaternion_arrtype_repr;
    PyQuaternionArrType_Type.tp_str = quaternion_arrtype_str;
    PyQuaternionArrType_Type.tp_base = &PyGenericArrType_Type;
    if (PyType_Ready(&PyQuaternionArrType_Type) < 0) {
        PyErr_Print();
        PyErr_SetString(PyExc_SystemError, "could not initialize PyQuaternionArrType_Type");
        return;
    }

    /* The array functions */
    PyArray_InitArrFuncs(&_PyQuaternion_ArrFuncs);
    _PyQuaternion_ArrFuncs.getitem = (PyArray_GetItemFunc*)QUATERNION_getitem;
    _PyQuaternion_ArrFuncs.setitem = (PyArray_SetItemFunc*)QUATERNION_setitem;
    _PyQuaternion_ArrFuncs.copyswap = (PyArray_CopySwapFunc*)QUATERNION_copyswap;
    _PyQuaternion_ArrFuncs.copyswapn = (PyArray_CopySwapNFunc*)QUATERNION_copyswapn;
    _PyQuaternion_ArrFuncs.compare = (PyArray_CompareFunc*)QUATERNION_compare;
    _PyQuaternion_ArrFuncs.argmax = (PyArray_ArgFunc*)QUATERNION_argmax;
    _PyQuaternion_ArrFuncs.nonzero = (PyArray_NonzeroFunc*)QUATERNION_nonzero;
    _PyQuaternion_ArrFuncs.fillwithscalar = (PyArray_FillWithScalarFunc*)QUATERNION_fillwithscalar;

    /* The quaternion array descr */
    quaternion_descr = PyObject_New(PyArray_Descr, &PyArrayDescr_Type);
    quaternion_descr->typeobj = &PyQuaternionArrType_Type;
    quaternion_descr->kind = 'q';
    quaternion_descr->type = 'j';
    quaternion_descr->byteorder = '=';
    quaternion_descr->type_num = 0; /* assigned at registration */
    quaternion_descr->elsize = 8*4;
    quaternion_descr->alignment = 8;
    quaternion_descr->subarray = NULL;
    quaternion_descr->fields = NULL;
    quaternion_descr->names = NULL;
    quaternion_descr->f = &_PyQuaternion_ArrFuncs;

    Py_INCREF(&PyQuaternionArrType_Type);
    quaternionNum = PyArray_RegisterDataType(quaternion_descr);

    if (quaternionNum < 0)
        return;

    register_cast_function(NPY_BOOL, quaternionNum, (PyArray_VectorUnaryFunc*)BOOL_to_quaternion);
    register_cast_function(NPY_BYTE, quaternionNum, (PyArray_VectorUnaryFunc*)BYTE_to_quaternion);
    register_cast_function(NPY_UBYTE, quaternionNum, (PyArray_VectorUnaryFunc*)UBYTE_to_quaternion);
    register_cast_function(NPY_SHORT, quaternionNum, (PyArray_VectorUnaryFunc*)SHORT_to_quaternion);
    register_cast_function(NPY_USHORT, quaternionNum, (PyArray_VectorUnaryFunc*)USHORT_to_quaternion);
    register_cast_function(NPY_INT, quaternionNum, (PyArray_VectorUnaryFunc*)INT_to_quaternion);
    register_cast_function(NPY_UINT, quaternionNum, (PyArray_VectorUnaryFunc*)UINT_to_quaternion);
    register_cast_function(NPY_LONG, quaternionNum, (PyArray_VectorUnaryFunc*)LONG_to_quaternion);
    register_cast_function(NPY_ULONG, quaternionNum, (PyArray_VectorUnaryFunc*)ULONG_to_quaternion);
    register_cast_function(NPY_LONGLONG, quaternionNum, (PyArray_VectorUnaryFunc*)LONGLONG_to_quaternion);
    register_cast_function(NPY_ULONGLONG, quaternionNum, (PyArray_VectorUnaryFunc*)ULONGLONG_to_quaternion);
    register_cast_function(NPY_FLOAT, quaternionNum, (PyArray_VectorUnaryFunc*)FLOAT_to_quaternion);
    register_cast_function(NPY_DOUBLE, quaternionNum, (PyArray_VectorUnaryFunc*)DOUBLE_to_quaternion);
    register_cast_function(NPY_LONGDOUBLE, quaternionNum, (PyArray_VectorUnaryFunc*)LONGDOUBLE_to_quaternion);
    register_cast_function(NPY_CFLOAT, quaternionNum, (PyArray_VectorUnaryFunc*)CFLOAT_to_quaternion);
    register_cast_function(NPY_CDOUBLE, quaternionNum, (PyArray_VectorUnaryFunc*)CDOUBLE_to_quaternion);
    register_cast_function(NPY_CLONGDOUBLE, quaternionNum, (PyArray_VectorUnaryFunc*)CLONGDOUBLE_to_quaternion);

#define REGISTER_UFUNC(name)\
    PyUFunc_RegisterLoopForType((PyUFuncObject *)PyDict_GetItemString(numpy_dict, #name),\
            quaternion_descr->type_num, quaternion_##name##_ufunc, arg_types, NULL)

#define REGISTER_SCALAR_UFUNC(name)\
    PyUFunc_RegisterLoopForType((PyUFuncObject *)PyDict_GetItemString(numpy_dict, #name),\
            quaternion_descr->type_num, quaternion_##name##_scalar_ufunc, arg_types, NULL)

    /* quat -> bool */
    arg_types[0] = quaternion_descr->type_num;
    arg_types[1] = NPY_BOOL;

    REGISTER_UFUNC(isnan);
    REGISTER_UFUNC(isinf);
    REGISTER_UFUNC(isfinite);
    /* quat -> double */
    arg_types[1] = NPY_DOUBLE;

    REGISTER_UFUNC(absolute);

    /* quat -> quat */
    arg_types[1] = quaternion_descr->type_num;

    REGISTER_UFUNC(log);
    REGISTER_UFUNC(exp);
    REGISTER_UFUNC(negative);
    REGISTER_UFUNC(conjugate);

    /* quat, quat -> bool */

    arg_types[2] = NPY_BOOL;

    REGISTER_UFUNC(equal);
    REGISTER_UFUNC(not_equal);
    REGISTER_UFUNC(less);
    REGISTER_UFUNC(less_equal);

    /* quat, double -> quat */

    arg_types[1] = NPY_DOUBLE;
    arg_types[2] = quaternion_descr->type_num;

    REGISTER_SCALAR_UFUNC(multiply);
    REGISTER_SCALAR_UFUNC(divide);
    REGISTER_SCALAR_UFUNC(power);

    /* quat, quat -> quat */

    arg_types[1] = quaternion_descr->type_num;

    REGISTER_UFUNC(add);
    REGISTER_UFUNC(subtract);
    REGISTER_UFUNC(multiply);
    REGISTER_UFUNC(divide);
    REGISTER_UFUNC(power);
    REGISTER_UFUNC(copysign);

    PyModule_AddObject(m, "quaternion", (PyObject *)&PyQuaternionArrType_Type);
}
Exemplo n.º 13
0
static int
CPyStreamWrapper_Read (CPyStreamWrapper *wrapper, void *buf, pguint32 offset,
    pguint32 count, pguint32 *read_)
{
    PyObject *result;
    pguint32 off, _read = 0;
    int retval = 1;
    char *tmp;
    char *ptr = (char*) buf;

    if (!wrapper->read || !wrapper->seek || !read_)
        return 0;

    if (offset != 0)
    {
        /* Move to the correct offset. */
        result = PyObject_CallFunction (wrapper->seek, "li", offset, SEEK_SET);
        if (!result)
        {
            PyErr_Print();
            retval = 0;
            goto end;
        }
        Py_DECREF (result);
    }
    if (count == 0)
    {
        /* Just a seek was wanted */
        goto end;
    }

    result = PyObject_CallFunction (wrapper->read, "l", count);
    if (!result)
    {
        PyErr_Print ();
        retval = 0;
        goto end;
    }
    
    if (!Bytes_Check (result))
    {
        Py_DECREF (result);
        PyErr_Print ();
        retval = 0;
        goto end;
    }
    
    _read = (pguint32) Bytes_GET_SIZE (result);
    tmp = Bytes_AS_STRING (result);

    off = 0;
    while ((_read - off) > SIZE_MAX)
    {
        memcpy (ptr + off, tmp + off, SIZE_MAX);
        off += SIZE_MAX;
    }
    memcpy (ptr + off, tmp + off, (size_t) (_read - off));
    Py_DECREF (result);

end:
    *read_ = _read;
    return retval;
}
Exemplo n.º 14
0
int AppMain()
{
	std::wstring exe_dir;

	// Get exe's directory
	{
		wchar_t exe_path_buf[MAX_PATH + 1];
		GetModuleFileName(NULL, exe_path_buf, MAX_PATH);

		exe_dir = exe_path_buf;

		size_t last_backslash_pos = exe_dir.find_last_of(L"\\/");
		if (last_backslash_pos >= 0)
		{
			exe_dir = exe_dir.substr(0, last_backslash_pos);
		}
		else
		{
			exe_dir = L"";
		}
	}

	// Setup environment variable "PATH"
	{
		std::wstring env_path;

		wchar_t tmp_buf[1];
		DWORD ret = GetEnvironmentVariable(L"PATH", tmp_buf, 0);
		if (ret > 0)
		{
			DWORD len = ret;
			wchar_t * buf = (wchar_t*)malloc((len + 1) * sizeof(wchar_t));

			GetEnvironmentVariable(L"PATH", buf, (len + 1) * sizeof(wchar_t));

			env_path = buf;

			free(buf);
		}

		env_path = exe_dir + L"/lib;" + env_path;

		SetEnvironmentVariable(L"PATH", env_path.c_str());
	}

	// Python home
	{
#if defined(_DEBUG)
		Py_SetPythonHome(PYTHON_INSTALL_PATH);
#else
		Py_SetPythonHome(const_cast<wchar_t*>(exe_dir.c_str()));
#endif //_DEBUG
	}

	// Python module search path
	{
		std::wstring python_path;

		python_path += exe_dir + L"/extension;";
		
		#if defined(_DEBUG)
		python_path += exe_dir + L";";
		python_path += exe_dir + L"/..;";
		python_path += std::wstring(PYTHON_INSTALL_PATH) + L"\\Lib;";
		python_path += std::wstring(PYTHON_INSTALL_PATH) + L"\\Lib\\site-packages;";
		python_path += std::wstring(PYTHON_INSTALL_PATH) + L"\\DLLs;";
		#else
		python_path += exe_dir + L"/library.zip;";
		python_path += exe_dir + L"/lib;";
		#endif
		
		Py_SetPath(python_path.c_str());
	}

	// Initialization
	Py_Initialize();

	// Setup sys.argv
	{
		wchar_t * cmdline = GetCommandLine();

		int argc;
		wchar_t ** argv = CommandLineToArgvW(cmdline, &argc);

		PySys_SetArgv(argc, argv);

		LocalFree(argv);
	}

	// Execute python side main script
	{
		PyObject * module = PyImport_ImportModule("keyhac_main");
		if (module == NULL)
		{
			PyErr_Print();
		}

		Py_XDECREF(module);
		module = NULL;
	}

	// Termination
	Py_Finalize();

	return 0;
}
Exemplo n.º 15
0
Bool
eval_jac_g(Index n, Number * x, Bool new_x,
	   Index m, Index nele_jac,
	   Index * iRow, Index * jCol, Number * values, UserDataPtr data)
{

	logger("[Callback:E] eval_jac_g");

	DispatchData *myowndata = (DispatchData *) data;
	UserDataPtr user_data = (UserDataPtr) myowndata->userdata;

	int i;
	long *rowd = NULL;
	long *cold = NULL;

	/* int dims[1]; */
	npy_intp dims[1];
	dims[0] = n;

	double *tempdata;

	if (myowndata->eval_grad_f_python == NULL)	/* Why??? */
		PyErr_Print();

	if (values == NULL) {
		/* import_array (); */
		import_array1(FALSE);

		PyObject *arrayx =
		    PyArray_SimpleNewFromData(1, dims, PyArray_DOUBLE,
					      (char *)x);
		if (!arrayx)
			return FALSE;

		PyObject *arglist;

		if (user_data != NULL)
			arglist = Py_BuildValue("(OOO)",
						arrayx, Py_True,
						(PyObject *) user_data);
		else
			arglist = Py_BuildValue("(OO)", arrayx, Py_True);

		PyObject *result =
		    PyObject_CallObject(myowndata->eval_jac_g_python, arglist);
		if (!result) {

			logger("[PyIPOPT] return from eval_jac_g is null\n");
			/* TODO: need to deal with reference counting here */
			return FALSE;
		}
		if (!PyTuple_Check(result)) {
			PyErr_Print();
		}
		PyArrayObject *row =
		    (PyArrayObject *) PyTuple_GetItem(result, 0);
		PyArrayObject *col =
		    (PyArrayObject *) PyTuple_GetItem(result, 1);

		if (!row || !col || !PyArray_Check(row) || !PyArray_Check(col)) {
			logger
			    ("[Error] there are problems with row or col in eval_jac_g.\n");
			PyErr_Print();
		}
		rowd = (long *)row->data;
		cold = (long *)col->data;

		for (i = 0; i < nele_jac; i++) {
			iRow[i] = (Index) rowd[i];
			jCol[i] = (Index) cold[i];
		}
		Py_CLEAR(arrayx);
		Py_DECREF(result);
		Py_CLEAR(arglist);
		logger("[Callback:R] eval_jac_g(1)");
	} else {
		PyObject *arrayx =
		    PyArray_SimpleNewFromData(1, dims, PyArray_DOUBLE,
					      (char *)x);

		if (!arrayx)
			return FALSE;

		if (new_x && myowndata->apply_new_python) {
			/* Call the python function to applynew */
			PyObject *arg1 = Py_BuildValue("(O)", arrayx);
			PyObject *tempresult =
			    PyObject_CallObject(myowndata->apply_new_python,
						arg1);
			if (tempresult == NULL) {
				logger("[Error] Python function apply_new returns NULL");
				Py_DECREF(arg1);
				return FALSE;
			}
			Py_DECREF(arg1);
			Py_DECREF(tempresult);
		}
		PyObject *arglist;
		if (user_data != NULL)
			arglist = Py_BuildValue("(OOO)",
						arrayx, Py_False,
						(PyObject *) user_data);
		else
			arglist = Py_BuildValue("(OO)", arrayx, Py_False);

		PyArrayObject *result = (PyArrayObject *) PyObject_CallObject(
        myowndata->eval_jac_g_python, arglist);

		if (result == NULL) {
      logger("[Error] Python function eval_jac_g returns NULL");
			PyErr_Print();
      return FALSE;
    }

    if (!PyArray_Check(result)) {
      logger("[Error] Python function eval_jac_g returns non-PyArray");
      Py_DECREF(result);
      return FALSE;
    }

		/*
		 * Code is buggy here. We assume that result is a double
		 * array
		 */
		assert(result->descr->type == 'd');
		tempdata = (double *)result->data;

		for (i = 0; i < nele_jac; i++)
			values[i] = tempdata[i];

		Py_DECREF(result);
		Py_CLEAR(arrayx);
		Py_CLEAR(arglist);
		logger("[Callback:R] eval_jac_g(2)");
	}
	logger("[Callback:R] eval_jac_g");
	return TRUE;
}
Exemplo n.º 16
0
PyObject * sipWrapRecord( Record * r, bool makeCopy, TableSchema * defaultType )
{
	PyObject * ret = 0;
	// First we convert to Record using sip methods
	static sipTypeDef * recordType = getRecordType( "blur.Stone", "Record" );
	sipTypeDef * type = recordType;
	if( type ) {
		if( makeCopy )
			ret = getSipAPI()->api_convert_from_new_type( new Record(*r), type, NULL );
		else {
			ret = getSipAPI()->api_convert_from_type( r, type, Py_None );
		}
	} else {
		LOG_1( "Stone.Record not found" );
		return 0;
	}

	Table * table = r->table();

	TableSchema * tableSchema = 0;
	
	if( table )
		tableSchema = table->schema();
	else if( defaultType )
		tableSchema = defaultType;
	else
		return ret;

	bool isErr = false;
	if( tableSchema ) {
		QString className = tableSchema->className();
	
		// Then we try to find the python class for the particular schema class type
		// from the desired module set using addSchemaCastModule
		// BORROWED ref
		PyObject * dict = getSchemaCastModule( tableSchema->schema() );
		if( dict ) {
			SIP_BLOCK_THREADS
			// BORROWED ref
			PyObject * klass = PyDict_GetItemString( dict, className.toLatin1().constData() );
			if( klass ) {
				PyObject * tuple = PyTuple_New(1);
				// Tuple now holds only ref to ret
				PyTuple_SET_ITEM( tuple, 0, ret );
				PyObject * result = PyObject_CallObject( klass, tuple );
				if( result ) {
					if( PyObject_IsInstance( result, klass ) == 1 ) {
						ret = result;
					} else {
						LOG_1( "Cast Ctor Result is not a subclass of " + className );
						Py_INCREF( ret );
						Py_DECREF( result );
					}
				} else {
					LOG_1( "runPythonFunction: Execution Failed, Error Was:\n" );
					PyErr_Print();
					isErr = true;
				}
				Py_DECREF( tuple );
			}
			SIP_UNBLOCK_THREADS
			if( isErr ) return 0;
		} else LOG_1( "No cast module set for schema" );
	} else LOG_1( "Table has no schema" );
Exemplo n.º 17
0
Bool
eval_h(Index n, Number * x, Bool new_x, Number obj_factor,
       Index m, Number * lambda, Bool new_lambda,
       Index nele_hess, Index * iRow, Index * jCol,
       Number * values, UserDataPtr data)
{
	logger("[Callback:E] eval_h");

	DispatchData *myowndata = (DispatchData *) data;
	UserDataPtr user_data = (UserDataPtr) myowndata->userdata;

	int i;
	npy_intp dims[1];
	npy_intp dims2[1];

	if (myowndata->eval_h_python == NULL) {
		logger("[Error] There is no eval_h assigned");
		return FALSE;
	}
	if (values == NULL) {
    logger("[Callback:E] eval_h (1a)");
		PyObject *newx = Py_True;
		PyObject *objfactor = Py_BuildValue("d", obj_factor);
		PyObject *lagrange = Py_True;

		PyObject *arglist;

		if (user_data != NULL) {
			arglist = Py_BuildValue(
          "(OOOOO)", newx, lagrange, objfactor, Py_True,
          (PyObject *) user_data);
    } else {
			arglist = Py_BuildValue(
          "(OOOO)", newx, lagrange, objfactor, Py_True);
    }

    if (arglist == NULL) {
      logger("[Error] failed to build arglist for eval_h");
			PyErr_Print();
      return FALSE;
    } else {
      logger("[Logspam] built arglist for eval_h");
    }

		PyObject *result = PyObject_CallObject(myowndata->eval_h_python, arglist);

    if (result == NULL) {
      logger("[Error] Python function eval_h returns NULL");
			PyErr_Print();
      return FALSE;
    } else {
      logger("[Logspam] Python function eval_h returns non-NULL");
    }

    int result_size = PyTuple_Size(result);

    if (result_size == -1) {
      logger("[Error] Python function eval_h returns non-PyTuple");
      Py_DECREF(result);
      return FALSE;
    }

    if (result_size != 2) {
      logger("[Error] Python function eval_h returns a tuple whose len != 2");
      Py_DECREF(result);
      return FALSE;
    }

    logger("[Callback:E] eval_h (tuple is the right length)");

		PyArrayObject *row = (PyArrayObject *) PyTuple_GetItem(result, 0);
		PyArrayObject *col = (PyArrayObject *) PyTuple_GetItem(result, 1);

		long *rdata = (long *)row->data;
		long *cdata = (long *)col->data;

		for (i = 0; i < nele_hess; i++) {
			iRow[i] = (Index) rdata[i];
			jCol[i] = (Index) cdata[i];
			/*
			 * logger("PyIPOPT_DEBUG %d, %d\n", iRow[i],
			 * jCol[i]);
			 */
		}

    logger("[Callback:E] eval_h (clearing stuff now)");

		Py_DECREF(objfactor);
		Py_DECREF(result);
		Py_CLEAR(arglist);
		logger("[Callback:R] eval_h (1b)");
	} else {
		logger("[Callback:R] eval_h (2a)");

		PyObject *objfactor = Py_BuildValue("d", obj_factor);

		dims[0] = n;
		PyObject *arrayx =
		    PyArray_SimpleNewFromData(1, dims, PyArray_DOUBLE,
					      (char *)x);
		if (!arrayx)
			return FALSE;

		if (new_x && myowndata->apply_new_python) {
			/* Call the python function to applynew  */
			PyObject *arg1 = Py_BuildValue("(O)", arrayx);
			PyObject *tempresult = PyObject_CallObject(
          myowndata->apply_new_python, arg1);
			if (tempresult == NULL) {
				logger("[Error] Python function apply_new returns NULL");
        PyErr_Print();
				Py_DECREF(arg1);
				return FALSE;
			}
			Py_DECREF(arg1);
			Py_DECREF(tempresult);
		}
		dims2[0] = m;
		PyObject *lagrangex = PyArray_SimpleNewFromData(
        1, dims2, PyArray_DOUBLE, (char *)lambda);
		if (!lagrangex)
			return FALSE;

		PyObject *arglist;

		if (user_data != NULL) {
			arglist = Py_BuildValue(
          "(OOOOO)", arrayx, lagrangex, objfactor, Py_False,
          (PyObject *) user_data);
    } else {
			arglist = Py_BuildValue(
          "(OOOO)", arrayx, lagrangex, objfactor, Py_False);
    }
		PyArrayObject *result = (PyArrayObject *) PyObject_CallObject(
        myowndata->eval_h_python, arglist);

		if (result == NULL) {
      logger("[Error] Python function eval_h returns NULL");
			PyErr_Print();
      return FALSE;
    }

    if (!PyArray_Check(result)) {
      logger("[Error] Python function eval_h returns non-PyArray");
      Py_DECREF(result);
      return FALSE;
    }

		double *tempdata = (double *)result->data;
		for (i = 0; i < nele_hess; i++) {
			values[i] = tempdata[i];
      logger("PyDebug %lf", values[i]);
		}
		Py_CLEAR(arrayx);
		Py_CLEAR(lagrangex);
		Py_CLEAR(objfactor);
		Py_DECREF(result);
		Py_CLEAR(arglist);
		logger("[Callback:R] eval_h (2b)");
	}
	return TRUE;
}
Exemplo n.º 18
0
static int 
TargetCall(WsXmlDocH doc, PyObject* instance, 
                 const char* opname, int nargs, ...)
{
    va_list vargs; 
    PyObject *pyargs = NULL; 
    PyObject *pyfunc = NULL; 
    PyObject *result = NULL; 
    WsmanStatus status;
    wsman_status_init(&status);

    pyargs = PyTuple_New(nargs); 
    pyfunc = PyObject_GetAttrString(instance, opname); 
    if (pyfunc == NULL)
    {
        PyErr_Print(); 
        PyErr_Clear(); 
        char* str = fmtstr("Python module does not contain \"%s\"", opname); 
        debug("%s", str); 
	status.fault_code = WSA_ENDPOINT_UNAVAILABLE;
	status.fault_detail_code = 0;

        free(str); 
        goto cleanup; 
    }
    if (! PyCallable_Check(pyfunc))
    {
        char* str = fmtstr("Python module attribute \"%s\" is not callable", 
                opname); 
        debug("%s", str); 
	status.fault_code = WSA_ENDPOINT_UNAVAILABLE;
	status.fault_detail_code = 0;
        free(str); 
        goto cleanup; 
    }
    
    va_start(vargs, nargs); 
    int i; 
    for (i = 0; i < nargs; ++i)
    {
        PyObject* arg = va_arg(vargs, PyObject*); 
        if (arg == NULL)
        {
            arg = Py_None; 
            Py_IncRef(arg); 
        }
        PyTuple_SET_ITEM(pyargs, i, arg); 
    }
    va_end(vargs); 
    result = PyObject_CallObject(pyfunc, pyargs);
    if (PyErr_Occurred())
    {
        status.fault_code = WSMAN_INTERNAL_ERROR;
	status.fault_detail_code = 0;
        PyErr_Clear(); 
        goto cleanup; 
    }

    if (! PyTuple_Check(result) || 
            (PyTuple_Size(result) != 2 && PyTuple_Size(result) != 1))
    {
        TARGET_THREAD_BEGIN_ALLOW;
        status.fault_msg = fmtstr("Python function \"%s\" didn't return a two-tuple", opname); 
	status.fault_code = WSMAN_INTERNAL_ERROR;
	status.fault_detail_code = 0;
        TARGET_THREAD_END_ALLOW; 
        goto cleanup; 
    }
    PyObject* code = PyTuple_GetItem(result, 0);
    PyObject* detail = Py_None; 
    if (PyTuple_Size(result) == 2)
    {
        detail = PyTuple_GetItem(result, 1); 
    }

    if (! PyInt_Check(code) || (! PyInt_Check(detail) && detail != Py_None))
    {
        TARGET_THREAD_BEGIN_ALLOW;
        status.fault_msg = fmtstr("Python function \"%s\" didn't return a {<int>, <int>) two-tuple", opname); 
	status.fault_code = WSMAN_INTERNAL_ERROR;
	status.fault_detail_code = 0;
        TARGET_THREAD_END_ALLOW; 
        goto cleanup; 
    }
    status.fault_code = PyInt_AsLong(code); 
    if (detail == Py_None)
    {
	status.fault_code = WSMAN_INTERNAL_ERROR;
	status.fault_detail_code = 0;
    }
    else
    {
        status.fault_detail_code = PyInt_AsLong(detail);
    }
cleanup:
    if (status.fault_code != WSMAN_RC_OK)
      wsman_generate_fault( doc, status.fault_code, status.fault_detail_code, status.fault_msg );
    Py_DecRef(pyargs);
    Py_DecRef(pyfunc);
    Py_DecRef(result);
 
    return status.fault_code != WSMAN_RC_OK; 
}
Exemplo n.º 19
0
// this should be equivalent to running
// python run_integrated.py 1999 700 715 --q1_window=1.0 --q3_window=1.0 --ssrcalc_window=10 -p hroest.srmpeptides_yeast --max_uis 5
//
int main(int argc, const char ** argv)
{
  python::list precursors_to_evaluate;
  double isotope_correction;
  python::object par; // parameter object
  SRMCollider::ExtendedRangetree::Rangetree_Q1_RT rangetree;
  SRMParameters params;

  std::string table_name = "hroest.srmPeptides_yeast";
  std::string mysql_config = "~/.my.cnf";

  double min_q1 = 700; 
  double max_q1 = 715; 
  double q1_window = 1.0/2.0;
  double q3_window = 1.0/2.0;
  double ssrcalc_window = 10/2.0;
  int max_uis = 5;
  int max_nr_isotopes = 3;
  bool ppm = false;
  double q3_lower = 400;
  double q3_upper = 1400;

  try {


  Py_Initialize();

  // now time to insert the current working directory into the Python search
  // path so module search can take advantage.  This must happen after Python
  // has been initialised
  boost::filesystem::path workingDir = boost::filesystem::complete("./").normalize();
  // TODO use filesystem or filesystem3
  PyObject* sysPath = PySys_GetObject("path");
  PyList_Insert( sysPath, 0, PyString_FromString(workingDir.string().c_str()));

  workingDir = boost::filesystem::complete("../").normalize();
  PyList_Insert( sysPath, 0, PyString_FromString(workingDir.string().c_str()));

  python::object ignored;

  std::cout << "Will try to import all the modules" << std::endl;
  python::object mMainModule = python::import("__main__");
  python::object precursor = boost::python::import("precursor");
  python::object collider = boost::python::import("collider");
  python::object MySQLdb = boost::python::import("MySQLdb");
  par = collider.attr("SRM_parameters")();
  std::cout << "Imported all the modules successfully, trying to get a db cusor..." << std::endl;

  ignored = par.attr("set_single_peptide_table")(table_name);
  ignored = par.attr("set_q3_range")(q3_lower, q3_upper);
  ignored = par.attr("set_default_vars")();
  ignored = par.attr("set_mysql_config")(mysql_config);
  python::object db = par.attr("get_db")();
  python::object cursor = db.attr("cursor")();
  std::cout << "Got a db cursor, trying to get precursors from the db..." << std::endl;

  python::object myprecursors = precursor.attr("Precursors")();
  myprecursors.attr("getFromDB")(par, cursor, min_q1 - q1_window, max_q1 + q1_window);
  std::cout << "Got all precursors from the db, trying to build a rangetree..." << std::endl;

  precursors_to_evaluate = python::extract<python::list>(myprecursors.attr("getPrecursorsToEvaluate")(min_q1, max_q1));
  isotope_correction = python::extract<double>(par.attr("calculate_isotope_correction")());
  //python::object r_tree = myprecursors.attr("build_extended_rangetree")();

  python::tuple alltuples = python::extract<python::tuple>(myprecursors.attr("get_alltuples_extended_rangetree")());
  rangetree.create_tree(alltuples);
  std::cout << "Built a rangetree, starting calculations..." << std::endl;

  SRMCollider::pyToC::initialize_param_obj(par, params);
  params.q3_window = q3_window;
  params.ppm = false;

  }
  // Catch any Python errors during set up and print them ...
  catch (python::error_already_set) {
    PyErr_Print();
  }

  for (int i = 0; i < precursors_to_evaluate.attr("__len__")(); i++)
  {
    python::object precursor = precursors_to_evaluate[i];
    if (i % 1000 == 0) std::cout << "doing " << i << std::endl;

    double ssrcalc= python::extract<double>(precursor.attr("ssrcalc"));
    double q1= python::extract<double>(precursor.attr("q1"));
    python::object o_transition_group = precursor.attr("get_tr")();
    long transition_group = python::extract<long>(o_transition_group);
    //python::object o_transition_group = precursor.attr("transition_group ");
    //long transition_group = python::extract<long>(precursor.attr("transition_group "));
    double ssrcalc_low = ssrcalc - ssrcalc_window + 0.001;
    double ssrcalc_high = ssrcalc + ssrcalc_window - 0.001;
    python::tuple py_transitions = python::extract<python::tuple>(precursor.attr("calculate_transitions_from_param")(par));

    //python::object transitions = precursor.attr("calculate_transitions_from_param")(par);

#if 0
    SRMCollider::IntegratedRun::_py_wrap_all_bitwise(py_transitions,
        q1 - q1_window, ssrcalc_low, q1 + q1_window, ssrcalc_high,
        transition_group, max_uis, q3_window, ppm, max_nr_isotopes,
        isotope_correction, par, rangetree);
#else

    double transitions_length = python::extract<double>(py_transitions.attr("__len__")());
    std::vector<SRMCollider::Common::SRMTransition> mytransitions(transitions_length);
    SRMCollider::IntegratedRun::_pyToC_integratedrunTransitions(py_transitions, mytransitions);

    std::vector<COMBINT> collisions_per_peptide; 
    SRMCollider::IntegratedRun::wrap_all_bitwise(mytransitions,
      q1 - q1_window, ssrcalc_low, q1 + q1_window, ssrcalc_high,
      transition_group, max_uis, q3_window, ppm, max_nr_isotopes, isotope_correction,
         params, rangetree, collisions_per_peptide);

    // Use the collisions_per_peptide vector (bitwise vector) to compute the non-UIS combinations
    std::vector<int> c_result;
    for(int i =1; i<= max_uis; i++) {
      std::set<COMBINT> combinations;
      SRMCollider::Combinatorics::get_non_uis_bitwise(collisions_per_peptide, transitions_length, i, combinations);
      c_result.push_back(combinations.size());
    }

#endif



            /*
            precursor.q1 - par.q1_window, ssrcalc_low, precursor.q1 + par.q1_window,  ssrcalc_high,
            precursor.transition_group, min(par.max_uis,len(transitions)), par.q3_window, par.ppm,
            par.isotopes_up_to, isotope_correction, par, r_tree)


  // Python wrapper for wrap_all
  python::list _py_wrap_all_bitwise(python::tuple py_transitions, double a, double b,
    double c, double d, long thistransitiongr, int max_uis, double q3window,
    bool ppm, int max_nr_isotopes, double isotope_correction, python::object par,
    SRMCollider::ExtendedRangetree::Rangetree_Q1_RT& rtree)
  {

            */


  }


/*
# python::exec( "for order in range(1,6):
#   sum_all = sum([p[0]*1.0/p[1] for p in prepare if p[3] == order]) 
#   nr_peptides = len([p for p in prepare if p[3] == order])
#   if not par.quiet and not nr_peptides ==0: print 'Order %s, Average non useable UIS %s' % (order, sum_all *1.0/ nr_peptides)")
*/




/*
 *
 *
 *
 *
  void wrap_all_bitwise(std::vector<Transition> mytransitions, double a, double b,
    double c, double d, long thistransitiongr, int max_uis, double q3window,
    bool ppm, int max_nr_isotopes, double isotope_correction, SRMParameters params,
    SRMCollider::ExtendedRangetree::Rangetree_Q1_RT& rtree, std::vector<COMBINT>& newcollperpep)
 *
 *
  python::list _py_wrap_all_bitwise(python::tuple py_transitions, double a, double b,
    double c, double d, long thistransitiongr, int max_uis, double q3window,
    bool ppm, int max_nr_isotopes, double isotope_correction, python::object par,
    SRMCollider::ExtendedRangetree::Rangetree_Q1_RT& rtree)
 *
progressm = progress.ProgressMeter(total=len(precursors_to_evaluate), unit='peptides')
prepare  = []
for precursor in precursors_to_evaluate:
    transitions = precursor.calculate_transitions_from_param(par)
    #correct rounding errors, s.t. we get the same results as before!
    ssrcalc_low = precursor.ssrcalc - par.ssrcalc_window + 0.001
    ssrcalc_high = precursor.ssrcalc + par.ssrcalc_window - 0.001
    try:
        result = c_integrated.wrap_all_bitwise(transitions,
            precursor.q1 - par.q1_window, ssrcalc_low, precursor.q1 + par.q1_window,  ssrcalc_high,
            precursor.transition_group, min(par.max_uis,len(transitions)), par.q3_window, par.ppm,
            par.isotopes_up_to, isotope_correction, par, r_tree)
    except ValueError: 
      print "Too many transitions for", precursor.modification
      continue
    for order in range(1,min(par.max_uis+1, len(transitions)+1)): 
        prepare.append( (result[order-1], collider.choose(len(transitions), 
            order), precursor.parent_id , order, exp_key)  )
    #//break;
    progressm.update(1)
*/



/*
db = par.get_db()
cursor = db.cursor()

mycollider = collider.SRMcollider()
par = collider.SRM_parameters()

*/



  /*


myprecursors = Precursors()
myprecursors.getFromDB(par, db.cursor(), min_q1 - par.q1_window, max_q1 + par.q1_window)
precursors_to_evaluate = myprecursors.getPrecursorsToEvaluate(min_q1, max_q1)
isotope_correction = par.calculate_isotope_correction()
r_tree = myprecursors.build_extended_rangetree ()

        bp::object ignored = bp::exec("hello = file('hello.txt', 'w')\n"
              "hello.write('Hello world!')\n"
              "hello.close()", mMainNamespace);
  */

}
Exemplo n.º 20
0
static list_t *
TargetEndpoints( void *self, void *data )
{
    int len, i;
    PyObject *instance = (PyObject *)data;
    PyObject *pyfunc, *pynamespaces = NULL;
    WsmanStatus status;
    wsman_status_init(&status);
    debug("TargetEndpoints(Python), data %p, instance %p", data, instance);

    /*
     * Get namespaces
     */
  
    list_t *namespaces = list_create(LISTCOUNT_T_MAX);

    pyfunc = PyObject_GetAttrString(instance, "namespaces"); 
    if (pyfunc == NULL)
    {
        PyErr_Print(); 
        PyErr_Clear(); 
        debug("Python module does not contain \"namespaces\""); 
	status.fault_code = WSA_ENDPOINT_UNAVAILABLE;
	status.fault_detail_code = 0;
        goto cleanup; 
    }
    if (! PyCallable_Check(pyfunc))
    {
        debug("Python module attribute \"namespaces\" is not callable"); 
	status.fault_code = WSA_ENDPOINT_UNAVAILABLE;
	status.fault_detail_code = 0;
        goto cleanup; 
    }
    pynamespaces = PyObject_CallObject(pyfunc, NULL);
    if (PyErr_Occurred())
    {
	status.fault_code = WSA_ENDPOINT_UNAVAILABLE;
	status.fault_detail_code = 0;
        PyErr_Clear();
        goto cleanup; 
    }

    if (! PyTuple_Check(pynamespaces))
    {
        TARGET_THREAD_BEGIN_ALLOW;
        debug("Python function \"namespaces\" didn't return a two-tuple"); 
	status.fault_code = WSA_ENDPOINT_UNAVAILABLE;
	status.fault_detail_code = 0;
        TARGET_THREAD_END_ALLOW; 
        goto cleanup; 
    }

    len = PyTuple_Size(pynamespaces);

    for (i = 0; i < len; ++i) {
      lnode_t *node;
      PyObject *ns, *prefix;
      PyObject* elem = PyTuple_GetItem(pynamespaces, i);
      if (! PyTuple_Check(elem)
	  || ! (PyTuple_Size(elem) == 2)) {
        TARGET_THREAD_BEGIN_ALLOW;
        debug("Python function \"namespaces\" didn't return a list of two-tuple");
	status.fault_code = WSA_ENDPOINT_UNAVAILABLE;
	status.fault_detail_code = 0;
        TARGET_THREAD_END_ALLOW; 
        goto cleanup; 
      }
      ns = PyTuple_GetItem(elem, 0);
      prefix = PyTuple_GetItem(elem, 1);
      if (!PyString_Check(ns)
	  || !PyString_Check(prefix)) {
        TARGET_THREAD_BEGIN_ALLOW;
        debug("Python function \"namespaces\" didn't return a list of [<string>,<string>] tuples");
	status.fault_code = WSA_ENDPOINT_UNAVAILABLE;
	status.fault_detail_code = 0;
        TARGET_THREAD_END_ALLOW; 
        goto cleanup; 
      }
      
      WsSupportedNamespaces *sup_ns = (WsSupportedNamespaces *)u_malloc(sizeof(WsSupportedNamespaces));
      sup_ns->ns = PyString_AsString(ns);
      sup_ns->class_prefix = PyString_AsString(prefix);
      node = lnode_create(ns);
      list_append(namespaces, node);
    }
cleanup:
    if (pyfunc) Py_DecRef(pyfunc);
    if (pynamespaces) Py_DecRef(pynamespaces);
  
    return namespaces;
}
Exemplo n.º 21
0
/*
 * Import modules embedded in the archive - return 0 on success
 */
int importModules()
{
	PyObject *marshal;
	PyObject *marshaldict;
	PyObject *loadfunc;
	PyObject *pyfile;
	TOC *ptoc;
	PyObject *co;
	PyObject *mod;
	PyObject *res;
	char buf[32];

	VS("importing modules from CArchive\n"); 

	/* Get the Python function marshall.load
		* Here we collect some reference to PyObject that we don't dereference
		* Doesn't matter because the objects won't be going away anyway.
		*/
	marshal = PyImport_ImportModule("marshal");
	marshaldict = PyModule_GetDict(marshal);
	loadfunc = PyDict_GetItemString(marshaldict, "loads");

	/* Iterate through toc looking for module entries (type 'm')
		* this is normally just bootstrap stuff (archive and iu)
		*/
	ptoc = f_tocbuff;
	while (ptoc < f_tocend) {
		if (ptoc->typcd == 'm' || ptoc->typcd == 'M') 
		{
			unsigned char *modbuf = extract(ptoc);

			/* .pyc/.pyo files have 8 bytes header. Skip it and get a Python
			 * string directly pointing at the marshalled code.
			 */
			PyObject *mods = PyString_FromStringAndSize(modbuf + 8,
				ntohl(ptoc->ulen) - 8);
            
			VS(ptoc->name);
			VS("\n");
			
			co = PyObject_CallFunction(loadfunc, "O", mods);
			mod = PyImport_ExecCodeModule(ptoc->name, co);

			/* Check for errors in loading */
			if (mod == NULL) {
				FATALERROR("mod is NULL - ");
				FATALERROR(ptoc->name);
			}
			if (PyErr_Occurred())
			{
				PyErr_Print();
				PyErr_Clear();
			}

			Py_DECREF(mods);
			free(modbuf);
		}
		ptoc = incrementTocPtr(ptoc); 
	}

	return 0;
}
Exemplo n.º 22
0
static char *
get_exc_trace()
{
    char *tbstr = NULL; 

    PyObject *iostrmod = NULL;
    PyObject *tbmod = NULL;
    PyObject *iostr = NULL;
    PyObject *obstr = NULL;
    PyObject *args = NULL;
    PyObject *newstr = NULL;
    PyObject *func = NULL;
    char* rv = NULL; 

    PyObject *type, *value, *traceback;
    TARGET_THREAD_BEGIN_BLOCK; 
    PyErr_Fetch(&type, &value, &traceback);
    debug("** type %p, value %p, traceback %p", type, value, traceback); 
    PyErr_Print(); 
    PyErr_Clear(); 
    PyErr_NormalizeException(&type, &value, &traceback);
    debug("** type %p, value %p, traceback %p", type, value, traceback); 

    iostrmod = PyImport_ImportModule("StringIO");
    if (iostrmod==NULL)
        TB_ERROR("can't import StringIO");

    iostr = PyObject_CallMethod(iostrmod, "StringIO", NULL);

    if (iostr==NULL)
        TB_ERROR("cStringIO.StringIO() failed");

    tbmod = PyImport_ImportModule("traceback");
    if (tbmod==NULL)
        TB_ERROR("can't import traceback");

    obstr = PyObject_CallMethod(tbmod, "print_exception",
        "(OOOOO)",
        type ? type : Py_None, 
        value ? value : Py_None,
        traceback ? traceback : Py_None,
        Py_None,
        iostr);

    if (obstr==NULL) 
    {
        PyErr_Print(); 
        TB_ERROR("traceback.print_exception() failed");
    }

    Py_DecRef(obstr);

    obstr = PyObject_CallMethod(iostr, "getvalue", NULL);
    if (obstr==NULL) 
        TB_ERROR("getvalue() failed.");

    if (!PyString_Check(obstr))
        TB_ERROR("getvalue() did not return a string");

    debug("%s", PyString_AsString(obstr)); 
    args = PyTuple_New(2);
    PyTuple_SetItem(args, 0, string2target("\n")); 
    PyTuple_SetItem(args, 1, string2target("<br>")); 
    
    func = PyObject_GetAttrString(obstr, "replace"); 
    //newstr = PyObject_CallMethod(obstr, "replace", args); 
    newstr = PyObject_CallObject(func, args); 

    tbstr = PyString_AsString(newstr); 

    rv = fmtstr("plugin:%s", tbstr); 

cleanup:
    PyErr_Restore(type, value, traceback);

    if (rv == NULL)
    {
        rv = tbstr ? tbstr : "";
    }

    Py_DecRef(func);
    Py_DecRef(args);
    Py_DecRef(newstr);
    Py_DecRef(iostr);
    Py_DecRef(obstr);
    Py_DecRef(iostrmod);
    Py_DecRef(tbmod);


    TARGET_THREAD_END_BLOCK; 
    return rv;
}
Exemplo n.º 23
0
int embed_sim_init(gpi_sim_info_t *info)
{
    FENTER

    int i;
    int ret = 0;

    /* Check that we are not already initialised */
    if (pEventFn)
        return ret;

    // Find the simulation root
    const char *dut = getenv("TOPLEVEL");

    if (dut != NULL) {
        if (!strcmp("", dut)) {
            /* Empty string passed in, treat as NULL */
            dut = NULL;
        } else {
            // Skip any library component of the toplevel
            char *dot = strchr(dut, '.');
            if (dot != NULL) {
                dut += (dot - dut + 1);
            }
        }
    }




    PyObject *cocotb_module, *cocotb_init, *cocotb_args, *cocotb_retval;
    PyObject *simlog_obj, *simlog_func;
    PyObject *argv_list, *argc, *arg_dict, *arg_value;

    cocotb_module = NULL;
    arg_dict = NULL;

    //Ensure that the current thread is ready to callthe Python C API
    PyGILState_STATE gstate = PyGILState_Ensure();

    if (get_module_ref(COCOTB_MODULE, &cocotb_module))
        goto cleanup;

    // Obtain the loggpi logger object
    simlog_obj = PyObject_GetAttrString(cocotb_module, "loggpi");

    if (simlog_obj == NULL) {
        PyErr_Print();
        fprintf(stderr, "Failed to to get simlog object\n");
    }

    simlog_func = PyObject_GetAttrString(simlog_obj, "_printRecord");
    if (simlog_func == NULL) {
        PyErr_Print();
        fprintf(stderr, "Failed to get the _printRecord method");
        goto cleanup;
    }

    if (!PyCallable_Check(simlog_func)) {
        PyErr_Print();
        fprintf(stderr, "_printRecord is not callable");
        goto cleanup;
    }

    set_log_handler(simlog_func);

    Py_DECREF(simlog_func);

    simlog_func = PyObject_GetAttrString(simlog_obj, "_willLog");
    if (simlog_func == NULL) {
        PyErr_Print();
        fprintf(stderr, "Failed to get the _willLog method");
        goto cleanup;
    }

    if (!PyCallable_Check(simlog_func)) {
        PyErr_Print();
        fprintf(stderr, "_willLog is not callable");
        goto cleanup;
    }

    set_log_filter(simlog_func);

    argv_list = PyList_New(0);
    for (i = 0; i < info->argc; i++) {
        arg_value = PyString_FromString(info->argv[i]);
        PyList_Append(argv_list, arg_value);
    }

    arg_dict = PyModule_GetDict(cocotb_module);
    PyDict_SetItemString(arg_dict, "argv", argv_list);

    argc = PyInt_FromLong(info->argc);
    PyDict_SetItemString(arg_dict, "argc", argc);

    if (!PyCallable_Check(simlog_func)) {
        PyErr_Print();
        fprintf(stderr, "_printRecord is not callable");
        goto cleanup;
    }

    LOG_INFO("Running on %s version %s", info->product, info->version);
    LOG_INFO("Python interpreter initialised and cocotb loaded!");

    // Now that logging has been set up ok we initialise the testbench
    if (-1 == PyObject_SetAttrString(cocotb_module, "SIM_NAME", PyString_FromString(info->product))) {
        PyErr_Print();
        fprintf(stderr, "Unable to set SIM_NAME");
        goto cleanup;
    }

    // Set language in use as an attribute to cocotb module, or None if not provided
    const char *lang = getenv("TOPLEVEL_LANG");
    PyObject* PyLang;
    if (lang)
        PyLang = PyString_FromString(lang);
    else
        PyLang = Py_None;

    if (-1 == PyObject_SetAttrString(cocotb_module, "LANGUAGE", PyLang)) {
        fprintf(stderr, "Unable to set LANGUAGE");
        goto cleanup;
    }

    // Hold onto a reference to our _fail_test function
    pEventFn = PyObject_GetAttrString(cocotb_module, "_sim_event");

    if (!PyCallable_Check(pEventFn)) {
        PyErr_Print();
        fprintf(stderr, "cocotb._sim_event is not callable");
        goto cleanup;
    }
    Py_INCREF(pEventFn);

    cocotb_init = PyObject_GetAttrString(cocotb_module, "_initialise_testbench");         // New reference

    if (cocotb_init == NULL || !PyCallable_Check(cocotb_init)) {
        if (PyErr_Occurred())
            PyErr_Print();
        fprintf(stderr, "Cannot find function \"%s\"\n", "_initialise_testbench");
        goto cleanup;
    }

    cocotb_args = PyTuple_New(1);
    if (dut == NULL)
        PyTuple_SetItem(cocotb_args, 0, Py_BuildValue(""));        // Note: This function “steals” a reference to o.
    else
        PyTuple_SetItem(cocotb_args, 0, PyString_FromString(dut));        // Note: This function “steals” a reference to o.
    cocotb_retval = PyObject_CallObject(cocotb_init, cocotb_args);

    if (cocotb_retval != NULL) {
        LOG_DEBUG("_initialise_testbench successful");
        Py_DECREF(cocotb_retval);
    } else {
        PyErr_Print();
        fprintf(stderr,"Cocotb initialisation failed - exiting\n");
    }

    FEXIT
    goto ok;

cleanup:
    ret = -1;
ok:
    if (cocotb_module) {
        Py_DECREF(cocotb_module);
    }
    if (arg_dict) {
        Py_DECREF(arg_dict);
    }
    PyGILState_Release(gstate);

    return ret;
}
Exemplo n.º 24
0
void WritePythonFile(const plFileName &fileName, const plFileName &path, hsStream *s)
{
    hsUNIXStream pyStream, glueStream;
    plFileName filePath;
    ST_ssize_t filestart = fileName.AsString().find_last('.');
    if (filestart >= 0)
        filePath = fileName.AsString().substr(filestart+1);
    else
        filePath = fileName;
    filePath = plFileName::Join(path, filePath + ".py");

    if (!pyStream.Open(filePath) || !glueStream.Open(glueFile))
    {
        ST::printf("Unable to open path {}, ", filePath);
        return;
    }

    ST::printf("==Packing {}, ", fileName);

    pyStream.FastFwd();
    uint32_t pyFileSize = pyStream.GetPosition();
    pyStream.Rewind();

    glueStream.FastFwd();
    uint32_t glueFileSize = glueStream.GetPosition();
    glueStream.Rewind();

    uint32_t totalSize = pyFileSize + glueFileSize + 2;

    char *code = new char[totalSize];

    uint32_t amountRead = pyStream.Read(pyFileSize, code);
    hsAssert(amountRead == pyFileSize, "Bad read");

    code[pyFileSize] = '\n';

    amountRead = glueStream.Read(glueFileSize, code+pyFileSize+1);
    hsAssert(amountRead == glueFileSize, "Bad read");

    code[totalSize-1] = '\0';

    // remove the CRs, they seem to give Python heartburn
    int k = 0;
    for (int i = 0; i < totalSize; i++)
    {
        if (code[i] != '\r')    // is it not a CR?
            code[k++] = code[i];
        // else
        //   skip the CRs
    }

    // import the module first, to make packages work correctly
    PyImport_ImportModule(fileName.AsString().c_str());
    PyObject* pythonCode = PythonInterface::CompileString(code, fileName);
    if (pythonCode)
    {
        // we need to find out if this is PythonFile module
        // create a module name... with the '.' as an X
        // and create a python file name that is without the ".py"
        PyObject* fModule = PythonInterface::CreateModule(fileName.AsString().c_str());
        // run the code
        if (PythonInterface::RunPYC(pythonCode, fModule) )
        {
    // set the name of the file (in the global dictionary of the module)
            PyObject* dict = PyModule_GetDict(fModule);
            PyObject* pfilename = PyString_FromString(fileName.AsString().c_str());
            PyDict_SetItemString(dict, "glue_name", pfilename);
    // next we need to:
    //  - create instance of class
            PyObject* getID = PythonInterface::GetModuleItem("glue_getBlockID",fModule);
            bool foundID = false;
            if ( getID!=nil && PyCallable_Check(getID) )
            {
                PyObject* id = PyObject_CallFunction(getID,nil);
                if ( id && PyInt_Check(id) )
                    foundID = true;
            }
            if ( foundID == false )     // then there was an error or no ID or somethin'
            {
                // oops, this is not a PythonFile modifier
                // re-read the source and compile it without the glue code this time
                pyStream.Rewind();
                amountRead = pyStream.Read(pyFileSize, code);
                hsAssert(amountRead == pyFileSize, "Bad read");
                code[amountRead] = '\n';
                code[amountRead+1] = '\0';
                k = 0;
                int len = strlen(code)+1;
                for (int i = 0; i < len; i++)
                {
                    if (code[i] != '\r')    // is it not a CR?
                        code[k++] = code[i];
                    // else
                    //   skip the CRs
                }
                pythonCode = PythonInterface::CompileString(code, fileName);
                hsAssert(pythonCode,"Not sure why this didn't compile the second time???");
                fputs("an import file ", stdout);
            }
            else
                fputs("a PythonFile modifier(tm) ", stdout);
        }
        else
        {
            fputs("......blast! Error during run-code!\n", stdout);

            char* errmsg;
            int chars_read = PythonInterface::getOutputAndReset(&errmsg);
            if (chars_read > 0)
            {
                puts(errmsg);
            }
        }
    }

    // make sure that we have code to save
    if (pythonCode)
    {
        int32_t size;
        char* pycode;
        PythonInterface::DumpObject(pythonCode,&pycode,&size);

        fputc('\n', stdout);
        // print any message after each module
        char* errmsg;
        int chars_read = PythonInterface::getOutputAndReset(&errmsg);
        if (chars_read > 0)
        {
            puts(errmsg);
        }
        s->WriteLE32(size);
        s->Write(size, pycode);
    }
    else
    {
        fputs("......blast! Compile error!\n", stdout);
        s->WriteLE32(0);

        PyErr_Print();
        PyErr_Clear();

        char* errmsg;
        int chars_read = PythonInterface::getOutputAndReset(&errmsg);
        if (chars_read > 0)
        {
            puts(errmsg);
        }
    }

    delete [] code;

    pyStream.Close();
    glueStream.Close();
}
Exemplo n.º 25
0
int main(int argc, char *argv[])
{
    PyObject *pName, *pModule, *pArgs, *pFunc, *pValue;
    int i;

    if (argc < 3) {
        printf("Usage: call_function python_source function_name\n");
        return 1;
    }

    /* Initialize the Python Interpreter */
    Py_Initialize();

    PyRun_SimpleString("import sys\n"
                       "sys.path.append('.')");

    /* Build the name object */
    pName = PyString_FromString(argv[1]);

    /* Load the module object */
    pModule = PyImport_Import(pName);
    Py_DECREF(pName);

    if (pModule != NULL) {
        /* pFunc is a borrowed reference */
        pFunc = PyObject_GetAttrString(pModule, argv[2]);

        if (pFunc && PyCallable_Check(pFunc)) {
            /* Prepare the argument list for the call */
            if( argc > 3 ) {
                pArgs = PyTuple_New(argc - 3);
                for (i = 0; i < argc - 3; ++i) {
                    pValue = PyInt_FromLong(atoi(argv[i + 3]));
                    if (!pValue) {
                        Py_DECREF(pArgs);
                        Py_DECREF(pModule);
                        fprintf(stderr, "Cannot convert argument\n");
                        return 1;
                    }
                    /* pValue reference stolen here: */
                    PyTuple_SetItem(pArgs, i, pValue);
                }
                pValue = PyObject_CallObject(pFunc, pArgs);
                Py_DECREF(pArgs);
                if (pValue != NULL) {
                    printf("Result of call: %ld\n", PyInt_AsLong(pValue));
                    Py_DECREF(pValue);
                }
                else {
                    Py_DECREF(pFunc);
                    Py_DECREF(pModule);
                    PyErr_Print();
                    fprintf(stderr,"Call failed\n");
                    return 1;
                }
            }
            else {
                pValue = PyObject_CallObject(pFunc, NULL);
            }
        }
        else {
            if (PyErr_Occurred())
                PyErr_Print();
            fprintf(stderr, "Cannot find function \"%s\"\n", argv[2]);
        }
        /* Clean up */
        Py_XDECREF(pFunc);
        Py_DECREF(pModule);
    }
    else {
        PyErr_Print();
        fprintf(stderr, "Failed to load \"%s\"\n", argv[1]);
        return 1;
    }
    /* Finish the Python Interpreter */
    Py_Finalize();

    return 0;
}
Exemplo n.º 26
0
Bool
eval_f(Index n, Number * x, Bool new_x, Number * obj_value, UserDataPtr data)
{
	logger("[Callback:E] eval_f");

	npy_intp dims[1];
	dims[0] = n;

	DispatchData *myowndata = (DispatchData *) data;
	UserDataPtr user_data = (UserDataPtr) myowndata->userdata;

	// import_array ();

	import_array1(FALSE);
	PyObject *arrayx =
	    PyArray_SimpleNewFromData(1, dims, PyArray_DOUBLE, (char *)x);
	if (!arrayx)
		return FALSE;

	if (new_x && myowndata->apply_new_python) {
		/* Call the python function to applynew */
		PyObject *arg1;
		arg1 = Py_BuildValue("(O)", arrayx);
		PyObject *tempresult = PyObject_CallObject(
        myowndata->apply_new_python, arg1);
		if (tempresult == NULL) {
			logger("[Error] Python function apply_new returns NULL");
      PyErr_Print();
			Py_DECREF(arg1);
			return FALSE;
		}
		Py_DECREF(arg1);
		Py_DECREF(tempresult);
	}

	PyObject *arglist;
	if (user_data != NULL) {
		arglist = Py_BuildValue("(OO)", arrayx, (PyObject *) user_data);
  } else {
		arglist = Py_BuildValue("(O)", arrayx);
  }

	PyObject *result = PyObject_CallObject(myowndata->eval_f_python, arglist);

	if (result == NULL) {
    logger("[Error] Python function eval_f returns NULL");
		PyErr_Print();
		Py_DECREF(arrayx);
		Py_CLEAR(arglist);
		return FALSE;
	}

	*obj_value = PyFloat_AsDouble(result);

  if (PyErr_Occurred()) {
    logger("[Error] Python function eval_f returns non-PyFloat");
		PyErr_Print();
		Py_DECREF(result);
		Py_DECREF(arrayx);
		Py_CLEAR(arglist);
		return FALSE;
  }

	Py_DECREF(result);
	Py_DECREF(arrayx);
	Py_CLEAR(arglist);
	logger("[Callback:R] eval_f");
	return TRUE;
}
Exemplo n.º 27
0
void
_Py_InitializeEx_Private(int install_sigs, int install_importlib)
{
    PyInterpreterState *interp;
    PyThreadState *tstate;
    PyObject *bimod, *sysmod, *pstderr;
    char *p;
    extern void _Py_ReadyTypes(void);

    if (initialized)
        return;
    initialized = 1;
    _Py_Finalizing = NULL;

#if defined(HAVE_LANGINFO_H) && defined(HAVE_SETLOCALE)
    /* Set up the LC_CTYPE locale, so we can obtain
       the locale's charset without having to switch
       locales. */
    setlocale(LC_CTYPE, "");
#endif

    if ((p = Py_GETENV("PYTHONDEBUG")) && *p != '\0')
        Py_DebugFlag = add_flag(Py_DebugFlag, p);
    if ((p = Py_GETENV("PYTHONVERBOSE")) && *p != '\0')
        Py_VerboseFlag = add_flag(Py_VerboseFlag, p);
    if ((p = Py_GETENV("PYTHONOPTIMIZE")) && *p != '\0')
        Py_OptimizeFlag = add_flag(Py_OptimizeFlag, p);
    if ((p = Py_GETENV("PYTHONDONTWRITEBYTECODE")) && *p != '\0')
        Py_DontWriteBytecodeFlag = add_flag(Py_DontWriteBytecodeFlag, p);
    /* The variable is only tested for existence here; _PyRandom_Init will
       check its value further. */
    if ((p = Py_GETENV("PYTHONHASHSEED")) && *p != '\0')
        Py_HashRandomizationFlag = add_flag(Py_HashRandomizationFlag, p);

    _PyRandom_Init();

    interp = PyInterpreterState_New();
    if (interp == NULL)
        Py_FatalError("Py_Initialize: can't make first interpreter");

    tstate = PyThreadState_New(interp);
    if (tstate == NULL)
        Py_FatalError("Py_Initialize: can't make first thread");
    (void) PyThreadState_Swap(tstate);

#ifdef WITH_THREAD
    /* We can't call _PyEval_FiniThreads() in Py_Finalize because
       destroying the GIL might fail when it is being referenced from
       another running thread (see issue #9901).
       Instead we destroy the previously created GIL here, which ensures
       that we can call Py_Initialize / Py_Finalize multiple times. */
    _PyEval_FiniThreads();

    /* Auto-thread-state API */
    _PyGILState_Init(interp, tstate);
#endif /* WITH_THREAD */

    _Py_ReadyTypes();

    if (!_PyFrame_Init())
        Py_FatalError("Py_Initialize: can't init frames");

    if (!_PyLong_Init())
        Py_FatalError("Py_Initialize: can't init longs");

    if (!PyByteArray_Init())
        Py_FatalError("Py_Initialize: can't init bytearray");

    if (!_PyFloat_Init())
        Py_FatalError("Py_Initialize: can't init float");

    interp->modules = PyDict_New();
    if (interp->modules == NULL)
        Py_FatalError("Py_Initialize: can't make modules dictionary");

    /* Init Unicode implementation; relies on the codec registry */
    if (_PyUnicode_Init() < 0)
        Py_FatalError("Py_Initialize: can't initialize unicode");
    if (_PyStructSequence_Init() < 0)
        Py_FatalError("Py_Initialize: can't initialize structseq");

    bimod = _PyBuiltin_Init();
    if (bimod == NULL)
        Py_FatalError("Py_Initialize: can't initialize builtins modules");
    _PyImport_FixupBuiltin(bimod, "builtins");
    interp->builtins = PyModule_GetDict(bimod);
    if (interp->builtins == NULL)
        Py_FatalError("Py_Initialize: can't initialize builtins dict");
    Py_INCREF(interp->builtins);

    /* initialize builtin exceptions */
    _PyExc_Init(bimod);

    sysmod = _PySys_Init();
    if (sysmod == NULL)
        Py_FatalError("Py_Initialize: can't initialize sys");
    interp->sysdict = PyModule_GetDict(sysmod);
    if (interp->sysdict == NULL)
        Py_FatalError("Py_Initialize: can't initialize sys dict");
    Py_INCREF(interp->sysdict);
    _PyImport_FixupBuiltin(sysmod, "sys");
    PySys_SetPath(Py_GetPath());
    PyDict_SetItemString(interp->sysdict, "modules",
                         interp->modules);

    /* Set up a preliminary stderr printer until we have enough
       infrastructure for the io module in place. */
    pstderr = PyFile_NewStdPrinter(fileno(stderr));
    if (pstderr == NULL)
        Py_FatalError("Py_Initialize: can't set preliminary stderr");
    _PySys_SetObjectId(&PyId_stderr, pstderr);
    PySys_SetObject("__stderr__", pstderr);
    Py_DECREF(pstderr);

    _PyImport_Init();

    _PyImportHooks_Init();

    /* Initialize _warnings. */
    _PyWarnings_Init();

    if (!install_importlib)
        return;

    import_init(interp, sysmod);

    /* initialize the faulthandler module */
    if (_PyFaulthandler_Init())
        Py_FatalError("Py_Initialize: can't initialize faulthandler");

    if (_PyTime_Init() < 0)
        Py_FatalError("Py_Initialize: can't initialize time");

    if (initfsencoding(interp) < 0)
        Py_FatalError("Py_Initialize: unable to load the file system codec");

    if (install_sigs)
        initsigs(); /* Signal handling stuff, including initintr() */

    if (_PyTraceMalloc_Init() < 0)
        Py_FatalError("Py_Initialize: can't initialize tracemalloc");

    initmain(interp); /* Module __main__ */
    if (initstdio() < 0)
        Py_FatalError(
            "Py_Initialize: can't initialize sys standard streams");

    /* Initialize warnings. */
    if (PySys_HasWarnOptions()) {
        PyObject *warnings_module = PyImport_ImportModule("warnings");
        if (warnings_module == NULL) {
            fprintf(stderr, "'import warnings' failed; traceback:\n");
            PyErr_Print();
        }
        Py_XDECREF(warnings_module);
    }

    if (!Py_NoSiteFlag)
        initsite(); /* Module site */
}
Exemplo n.º 28
0
Bool
eval_g(Index n, Number * x, Bool new_x, Index m, Number * g, UserDataPtr data)
{

	logger("[Callback:E] eval_g");

	DispatchData *myowndata = (DispatchData *) data;
	UserDataPtr user_data = (UserDataPtr) myowndata->userdata;

	if (myowndata->eval_g_python == NULL)
		PyErr_Print();
	/* int dims[1]; */
	npy_intp dims[1];
	int i;
	double *tempdata;

	dims[0] = n;
	// import_array ();

	import_array1(FALSE);

	/*
	 * PyObject *arrayx = PyArray_FromDimsAndData(1, dims, PyArray_DOUBLE
	 * , (char*) x);
	 */
	PyObject *arrayx =
	    PyArray_SimpleNewFromData(1, dims, PyArray_DOUBLE, (char *)x);
	if (!arrayx)
		return FALSE;

	if (new_x && myowndata->apply_new_python) {
		/* Call the python function to applynew */
		PyObject *arg1 = Py_BuildValue("(O)", arrayx);
		PyObject *tempresult = PyObject_CallObject(
        myowndata->apply_new_python, arg1);
		if (tempresult == NULL) {
			logger("[Error] Python function apply_new returns NULL");
      PyErr_Print();
			Py_DECREF(arg1);
			return FALSE;
		}
		Py_DECREF(arg1);
		Py_DECREF(tempresult);
	}

	PyObject *arglist;
	if (user_data != NULL)
		arglist = Py_BuildValue("(OO)", arrayx, (PyObject *) user_data);
	else
		arglist = Py_BuildValue("(O)", arrayx);

	PyArrayObject *result = (PyArrayObject *) PyObject_CallObject(
      myowndata->eval_g_python, arglist);

  if (result == NULL) {
    logger("[Error] Python function eval_g returns NULL");
		PyErr_Print();
    return FALSE;
  }
  
  if (!PyArray_Check(result)) {
    logger("[Error] Python function eval_g returns non-PyArray");
    Py_DECREF(result);
    return FALSE;
  }

	tempdata = (double *)result->data;
	for (i = 0; i < m; i++) {
		g[i] = tempdata[i];
	}

	Py_DECREF(result);
	Py_CLEAR(arrayx);
	Py_CLEAR(arglist);
	logger("[Callback:R] eval_g");
	return TRUE;
}
PythonScripting::PythonScripting(ApplicationWindow *parent)
: ScriptingEnv(parent, langName)
{
  PyObject *mainmod=NULL, *qtimod=NULL, *sysmod=NULL;
  math = NULL;
  sys = NULL;
  if (Py_IsInitialized())
  {
    PyEval_AcquireLock();
    mainmod = PyImport_ImportModule("__main__");
    if (!mainmod)
    {
      PyErr_Print();
      PyEval_ReleaseLock();
      return;
    }
    globals = PyModule_GetDict(mainmod);
    Py_DECREF(mainmod);
  } else {
    PyEval_InitThreads ();
    Py_Initialize ();
    if (!Py_IsInitialized ())
      return;
    initqti();

    mainmod = PyImport_AddModule("__main__");
    if (!mainmod)
    {
      PyEval_ReleaseLock();
      PyErr_Print();
      return;
    }
    globals = PyModule_GetDict(mainmod);
  }

  if (!globals)
  {
    PyErr_Print();
    PyEval_ReleaseLock();
    return;
  }
  Py_INCREF(globals);
 
  math = PyDict_New();
  if (!math)
    PyErr_Print();
  
  qtimod = PyImport_ImportModule("qti");
  if (qtimod)
  {
    PyDict_SetItemString(globals, "qti", qtimod);
    PyObject *qtiDict = PyModule_GetDict(qtimod);
    setQObject(Parent, "app", qtiDict);
    PyDict_SetItemString(qtiDict, "mathFunctions", math);
    Py_DECREF(qtimod);
  } else
    PyErr_Print();

  sysmod = PyImport_ImportModule("sys");
  if (sysmod)
  {
    sys = PyModule_GetDict(sysmod);
    Py_INCREF(sys);
  } else
    PyErr_Print();
  
  PyEval_ReleaseLock();

#ifdef Q_WS_WIN
  loadInitFile(QDir::homeDirPath()+"qtiplotrc") ||
    loadInitFile(qApp->applicationDirPath()+"qtiplotrc") ||
#else
  loadInitFile(QDir::homeDirPath()+"/.qtiplotrc") ||
    loadInitFile(QDir::rootDirPath()+"etc/qtiplotrc") ||
#endif
  loadInitFile("qtiplotrc");
  
  initialized=true;
}
Exemplo n.º 30
0
void init_uwsgi_vars() {

	PyObject *pysys, *pysys_dict, *pypath;

	PyObject *modules = PyImport_GetModuleDict();
	PyObject *tmp_module;

	/* add cwd to pythonpath */
	pysys = PyImport_ImportModule("sys");
	if (!pysys) {
		PyErr_Print();
		exit(1);
	}
	pysys_dict = PyModule_GetDict(pysys);

#ifdef PYTHREE
	// fix stdout and stderr
	PyObject *new_stdprint = PyFile_NewStdPrinter(2);
	PyDict_SetItemString(pysys_dict, "stdout", new_stdprint);
	PyDict_SetItemString(pysys_dict, "__stdout__", new_stdprint);
	PyDict_SetItemString(pysys_dict, "stderr", new_stdprint);
	PyDict_SetItemString(pysys_dict, "__stderr__", new_stdprint);
#endif
	pypath = PyDict_GetItemString(pysys_dict, "path");
	if (!pypath) {
		PyErr_Print();
		exit(1);
	}

	if (PyList_Insert(pypath, 0, UWSGI_PYFROMSTRING(".")) != 0) {
		PyErr_Print();
	}

	struct uwsgi_string_list *uppp = up.python_path;
	while(uppp) {
		if (PyList_Insert(pypath, 0, UWSGI_PYFROMSTRING(uppp->value)) != 0) {
			PyErr_Print();
		}
		else {
			uwsgi_log("added %s to pythonpath.\n", uppp->value);
		}

		uppp = uppp->next;
	}

	struct uwsgi_string_list *uppma = up.pymodule_alias;
	while(uppma) {
		// split key=value
		char *value = strchr(uppma->value, '=');
		if (!value) {
			uwsgi_log("invalid pymodule-alias syntax\n");
			goto next;
		}
		value[0] = 0;
		if (!strchr(value + 1, '/')) {
			// this is a standard pymodule
			tmp_module = PyImport_ImportModule(value + 1);
			if (!tmp_module) {
				PyErr_Print();
				exit(1);
			}

			PyDict_SetItemString(modules, uppma->value, tmp_module);
		}
		else {
			// this is a filepath that need to be mapped
			tmp_module = uwsgi_pyimport_by_filename(uppma->value, value + 1);
			if (!tmp_module) {
				PyErr_Print();
				exit(1);
			}
		}
		uwsgi_log("mapped virtual pymodule \"%s\" to real pymodule \"%s\"\n", uppma->value, value + 1);
		// reset original value
		value[0] = '=';

next:
		uppma = uppma->next;
	}

}