bool PythonInterpreter::runScript(const char* filename, const char* shortName) {
    PyEval_RestoreThread(state);

    PyObject* script = PyFile_FromString(const_cast<char*>(filename),
        const_cast<char*>("r"));
    if (script) {
        PyObject* ans = PyRun_File(PyFile_AsFile(script),
            const_cast<char*>(shortName),
            Py_file_input, mainNamespace, mainNamespace);
        Py_DECREF(script);

        if (ans) {
            Py_DECREF(ans);
            state = PyEval_SaveThread();
            return true;
        } else {
            PyErr_Print();
            state = PyEval_SaveThread();
            return false;
        }
    } else {
        state = PyEval_SaveThread();
        return false;
    }
}
Exemple #2
0
void
av::gua::Viewer::run() {

  ::gua::Logger::enable_debug = false;

  if (!m_renderer) {
    m_renderer = new av::gua::Renderer(new ::gua::Renderer());
  }


#if defined(AVANGO_PHYSICS_SUPPORT)
  if (Physics.getValue().isValid()) {
    Physics.getValue()->State.setValue(static_cast<int>(av::gua::Physics::RunningState::RUNNING));
  }
#endif

  PyThreadState* save_state(PyEval_SaveThread());

  m_ticker.on_tick.connect([&,this]() {
    PyEval_RestoreThread(save_state);

    frame();

    save_state = PyEval_SaveThread();
  });

  m_loop.start();

  for (auto& window: Windows.getValue()) {
    window->close();
  }

}
Exemple #3
0
static void *
rpmtsCallback(const void * hd, const rpmCallbackType what,
		         const rpm_loff_t amount, const rpm_loff_t total,
	                 const void * pkgKey, rpmCallbackData data)
{
    Header h = (Header) hd;
    struct rpmtsCallbackType_s * cbInfo = data;
    PyObject * pkgObj = (PyObject *) pkgKey;
    PyObject * args, * result;
    static FD_t fd;

    if (cbInfo->cb == Py_None) return NULL;

    /* Synthesize a python object for callback (if necessary). */
    if (pkgObj == NULL) {
	if (h) {
	    pkgObj = Py_BuildValue("s", headerGetString(h, RPMTAG_NAME));
	} else {
	    pkgObj = Py_None;
	    Py_INCREF(pkgObj);
	}
    } else
	Py_INCREF(pkgObj);

    PyEval_RestoreThread(cbInfo->_save);

    args = Py_BuildValue("(iLLOO)", what, amount, total, pkgObj, cbInfo->data);
    result = PyEval_CallObject(cbInfo->cb, args);
    Py_DECREF(args);
    Py_DECREF(pkgObj);

    if (!result) {
	die(cbInfo->cb);
    }

    if (what == RPMCALLBACK_INST_OPEN_FILE) {
	int fdno;

        if (!PyArg_Parse(result, "i", &fdno)) {
	    die(cbInfo->cb);
	}
	Py_DECREF(result);
	cbInfo->_save = PyEval_SaveThread();

	fd = fdDup(fdno);
	fcntl(Fileno(fd), F_SETFD, FD_CLOEXEC);

	return fd;
    } else
    if (what == RPMCALLBACK_INST_CLOSE_FILE) {
	Fclose (fd);
    }

    Py_DECREF(result);
    cbInfo->_save = PyEval_SaveThread();

    return NULL;
}
Exemple #4
0
//---------------------------------------------------------
// Pass messages into the Python interpreter main thread,
// which is expected to implement an event loop around calls
// to tart_wait() to retrieve these messages.
//
void Tart::do_postMessage(QString msg) {
    // qDebug() << QThread::currentThreadId() << "Tart: do_postMessage(" << msg << ")";

    QByteArray bytes = msg.toUtf8();

    // PyGILState_STATE gil_state = PyGILState_Ensure();
    PyEval_RestoreThread(tart_pystate);

    // qDebug() << "tart_wait bytes" << bytes.size();
    PyObject * arglist = Py_BuildValue("(s#)", bytes.constData(), bytes.size());
    // ran out of memory: fail!
    if (arglist == NULL) {
        qDebug() << "Py_BuildValue() returned NULL!";
        // should probably do something more significant here
        tart_pystate = PyEval_SaveThread();
        // PyGILState_Release(gil_state);
        return;
    } else {
        // qDebug() << "postMessage() built" << arglist;
    }

    // call the callback to send message to Python
    PyObject * result = PyObject_CallObject(event_callback, arglist);
    Py_DECREF(arglist);

    // qDebug() << "callback returned" << result;

    // TODO handle exceptions from the call, either by exiting the event
    // loop (maybe only during development?) or by dumping a traceback,
    // setting a flag, and continuing on.
    bool is_SystemExit = false;

    if (result == NULL) {   // exception during call
        // qDebug() << "exception during event delivery";

        // see http://computer-programming-forum.com/56-python/a81eae52ca74e6c1.htm
        // Calling PyErr_Print() will actually terminate the process if
        // SystemExit is the exception!
        if (PyErr_ExceptionMatches(PyExc_SystemExit))
            is_SystemExit = true;
        else
            PyErr_Print();
    }
    else
        Py_DECREF(result);

    // PyGILState_Release(gil_state);
    tart_pystate = PyEval_SaveThread();

    if (is_SystemExit) {
        qDebug() << "do_post: SystemExit from delivery";
        m_thread->exit(3);
    }

    // qDebug() << QThread::currentThreadId() << "Tart: do_postMessage done";
    return;
}
Exemple #5
0
//---------------------------------------------------------
// Pass push messages into the Python interpreter main thread,
// if it has implemented an onPushReceived() method.
//
void Tart::pushReceived(const QString & id, const QByteArray & bytes, bool wantsAck) {
    qDebug() << QThread::currentThreadId() << "Tart: pushReceived" << id << wantsAck << bytes.size();

    // FIXME: this should probably be checked inside the tart_pystate context
    // where the GIL is held, not outside.
    // Ignore data if no callback has been registered.
    if (!push_callback)
        return;

    PyEval_RestoreThread(tart_pystate);

    PyObject * arglist = Py_BuildValue("(sy#i)",
        id.toUtf8().constData(),
        bytes.constData(), bytes.size(),
        wantsAck
        );
    // ran out of memory: fail!
    if (arglist == NULL) {
        qDebug() << "Py_BuildValue() returned NULL!";
        // should probably do something more significant here
        tart_pystate = PyEval_SaveThread();
        return;
    }

    // call the callback to send message to Python
    PyObject * result = PyObject_CallObject(push_callback, arglist);
    Py_DECREF(arglist);

    // TODO handle exceptions from the call, either by exiting the event
    // loop (maybe only during development?) or by dumping a traceback,
    // setting a flag, and continuing on.
    bool is_SystemExit = false;

    if (result == NULL) {   // exception during call
        // see http://computer-programming-forum.com/56-python/a81eae52ca74e6c1.htm
        // Calling PyErr_Print() will actually terminate the process if
        // SystemExit is the exception!
        if (PyErr_ExceptionMatches(PyExc_SystemExit))
            is_SystemExit = true;
        else
            PyErr_Print();
    }
    else
        Py_DECREF(result);

    tart_pystate = PyEval_SaveThread();

    if (is_SystemExit) {
        qDebug() << "do_post: SystemExit from delivery";
        m_thread->exit(3);
    }

    return;
}
Exemple #6
0
void call_event_hook_callback(void * event)
    {
    // qDebug() << QThread::currentThreadId() << "call_event_hook_callback: begin";

    // PyGILState_STATE gil_state = PyGILState_Ensure();
    PyEval_RestoreThread(tart_pystate);

    PyObject * arglist = Py_BuildValue("(i)", event);
    // ran out of memory: fail!
    if (arglist == NULL)
        {
        qDebug() << "Py_BuildValue() returned NULL!";
        // should probably do something more significant here

        // PyGILState_Release(gil_state);
        tart_pystate = PyEval_SaveThread();
        return;
        }

    // call the callback to send message to Python
    PyObject * result = PyObject_CallObject(event_hook_callback, arglist);
    Py_DECREF(arglist);

    // TODO handle exceptions from the call, either by exiting the event
    // loop (maybe only during development?) or by dumping a traceback,
    // setting a flag, and continuing on.
    bool is_SystemExit = false;

    if (result == NULL)     // exception during call
        {
        // see http://computer-programming-forum.com/56-python/a81eae52ca74e6c1.htm
        // Calling PyErr_Print() will actually terminate the process if
        // SystemExit is the exception!
        if (PyErr_ExceptionMatches(PyExc_SystemExit))
            is_SystemExit = true;
        else
            PyErr_Print();
        }
    else
        Py_DECREF(result);

    // PyGILState_Release(gil_state);
    tart_pystate = PyEval_SaveThread();

    if (is_SystemExit)
        {
        qDebug() << "event_hook: SystemExit";
        QThread::currentThread()->exit(3);
        }

    // qDebug() << QThread::currentThreadId() << "call_event_hook_callback: end";

    return;
    }
Exemple #7
0
PythonLoader::PythonLoader(QObject *parent) : QObject(parent)
{

    if (!Py_IsInitialized())
    {
        QString sysPath = QCoreApplication::applicationDirPath();
        QString programPath = sysPath + "/thirdparty/Python/bin/python3";
        wchar_t* programName = new wchar_t[programPath.length() + 1];
        programPath.toWCharArray(programName);
        programName[programPath.length()] = 0;

        Py_SetProgramName(programName);
        wprintf(L"python prefix path: %S\n", Py_GetPrefix());
        wprintf(L"python full path: %S\n", Py_GetProgramFullPath());
        Py_Initialize();
        QStringList paths = {sysPath+"/thirdparty/Python/lib/python3.4", sysPath+"/thirdparty/Python/lib/python3.4/plat-linux",
                             sysPath+"/thirdparty/Python/lib/python3.4/lib-dynload", sysPath+"/thirdparty/Python/lib/python3.4/site-packages",
                            sysPath, sysPath+"/thirdparty/Python/lib", sysPath+"/thirdparty/Python/bin"};
        QString wholePath = paths.join(":");
        PySys_SetPath(wholePath.toStdWString().c_str());

        getSipAPI();
        PyEval_InitThreads();
        PyEval_SaveThread();
    }
}
Exemple #8
0
static int
rpmts_SolveCallback(rpmts ts, rpmds ds, const void * data)
{
    struct rpmtsCallbackType_s * cbInfo = (struct rpmtsCallbackType_s *) data;
    PyObject * args, * result;
    int res = 1;

    if (cbInfo->tso == NULL) return res;
    if (cbInfo->cb == Py_None) return res;

    PyEval_RestoreThread(cbInfo->_save);

    args = Py_BuildValue("(Oissi)", cbInfo->tso,
		rpmdsTagN(ds), rpmdsN(ds), rpmdsEVR(ds), rpmdsFlags(ds));
    result = PyEval_CallObject(cbInfo->cb, args);
    Py_DECREF(args);

    if (!result) {
	die(cbInfo->cb);
    } else {
	if (PyInt_Check(result))
	    res = PyInt_AsLong(result);
	Py_DECREF(result);
    }

    cbInfo->_save = PyEval_SaveThread();

    return res;
}
Exemple #9
0
static PyObject *
nis_cat (PyObject *self, PyObject *args, PyObject *kwdict)
{
	char *domain = NULL;
	char *map;
	struct ypall_callback cb;
	struct ypcallback_data data;
	PyObject *dict;
	int err;
	static char *kwlist[] = {"map", "domain", NULL};

	if (!PyArg_ParseTupleAndKeywords(args, kwdict, "s|s:cat",
				         kwlist, &map, &domain))
		return NULL;
	if (!domain && ((err = yp_get_default_domain(&domain)) != 0))
		return nis_error(err);
	dict = PyDict_New ();
	if (dict == NULL)
		return NULL;
	cb.foreach = (foreachfunc)nis_foreach;
	data.dict = dict;
	map = nis_mapname (map, &data.fix);
	cb.data = (char *)&data;
	data.state = PyEval_SaveThread();
	err = yp_all (domain, map, &cb);
	PyEval_RestoreThread(data.state);
	if (err != 0) {
		Py_DECREF(dict);
		return nis_error(err);
	}
	return dict;
}
// 초기화
CDummyClientManager::CDummyClientManager(void)
{
	g_dummyClientManager = this;

	m_highestIndex = 0;
	m_curIndex = 0;	
	m_maxLimitIndex = 999999;	

	// 파이썬 초기화
	Py_Initialize();
	PyEval_InitThreads();
	mainThreadState = PyEval_SaveThread();
	PyGILState_STATE gilState;

	gilState = PyGILState_Ensure();

	PyImport_AddModule("pythonCallbackModule");
	Py_InitModule("pythonCallbackModule", modules);

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

	// 메인 스크립트 로드
	CString log = ( SetMainScript() == false ) ? L"mainscript 로드 실패" : L"mainscript 로드 성공";	
	CtesttoolDlg* dlg = (CtesttoolDlg*)AfxGetApp()->m_pMainWnd;
	dlg->addMainLog( log );
	dlg->showMainLog();
}
void
BeginAllowThreads(PyThreadState **state)
{
    assert(state);
    assert(*state == NULL);
    (*state) = PyEval_SaveThread();
}
Exemple #12
0
void
QPythonPriv::leave()
{
    assert(state == NULL);
    state = PyEval_SaveThread();
    mutex.unlock();
}
 void redo()
 { 
     if (!done_ && PyEval_ThreadsInitialized()) { 
         save_ = PyEval_SaveThread(); 
         done_ = true; 
     } 
 }
bool PythonInterpreter::runScript(const char* code) {
    PyEval_RestoreThread(state);

    PyObject* ans = PyRun_String(const_cast<char*>(code), Py_file_input,
        mainNamespace, mainNamespace);
    if (ans) {
        Py_DECREF(ans);
        state = PyEval_SaveThread();
        return true;
    } else {
        PyErr_Print();
        PyErr_Clear();
        state = PyEval_SaveThread();
        return false;
    }
}
bool PythonInterpreter::compileScript(const char* code) {
    PyEval_RestoreThread(state);

    PyObject* ans = Py_CompileString(const_cast<char*>(code), "<script>",
        Py_file_input);
    if (ans) {
        Py_DECREF(ans);
        state = PyEval_SaveThread();
        return true;
    } else {
        PyErr_Print();
        PyErr_Clear();
        state = PyEval_SaveThread();
        return false;
    }
}
int main(int argc, char* argv[])
{
    PyEval_InitThreads();
    Py_Initialize();
    PyObject* sysPath = PySys_GetObject((char*) "path");
    PyList_Append(sysPath, PyString_FromString("."));

    PyThreadState* save = PyEval_SaveThread();

    pthread_t tid1, tid2;
    char* tname1 = "worker1";
    char* tname2 = "worker2";
    pthread_create(&tid1, NULL, &run_python_function, &tname1);
    pthread_create(&tid2, NULL, &run_python_function, &tname2);

    for (int i = 0; i < 5; i++)
    {
        printf("main thread is running\n");
        sleep(1);
    }

    stop_event = 1;
    pthread_join(tid1, NULL);
    pthread_join(tid2, NULL);

    printf("finish\n");

    PyEval_RestoreThread(save);
    Py_Finalize();

    pthread_exit(NULL);

    return 0;
}
Exemple #17
0
static PyObject * p_loop_or_dispatch (int dispatch, PyObject *self, PyObject *args)
{
  pcap_t * ppcap;
  thread_state ts;
  int cnt;
  int rv;
  int release_thread;
  if (!PyArg_ParseTuple(args, "liOOii", &ppcap, &cnt, &ts.pycallback, &ts.user, &ts.use_bytearray, &release_thread)) return NULL;
  Py_INCREF(ts.user);

  ts.ppcap = ppcap;
  ts.exception = 0;
  ts.release_thread = release_thread;
  if (release_thread) ts.ts = PyEval_SaveThread();

  if (dispatch)
    rv = pcap_loop(ppcap, cnt, ld_callback, (u_char *)&ts);
  else
    rv = pcap_dispatch(ppcap, cnt, ld_callback, (u_char *)&ts);

  if (release_thread) PyEval_RestoreThread(ts.ts);

  Py_DECREF(ts.user);

  if (ts.exception) return NULL;

  return Py_BuildValue("i", rv);
}
Exemple #18
0
// Device.get_file {{{
static PyObject *
Device_get_file(Device *self, PyObject *args) {
    PyObject *stream, *callback = NULL, *errs;
    ProgressCallback cb;
    unsigned long fileid;
    int ret;

    ENSURE_DEV(NULL); ENSURE_STORAGE(NULL);


    if (!PyArg_ParseTuple(args, "kO|O", &fileid, &stream, &callback)) return NULL; 
    errs = PyList_New(0);
    if (errs == NULL) { PyErr_NoMemory(); return NULL; }
    if (callback == NULL || !PyCallable_Check(callback)) callback = NULL;

    cb.obj = callback; cb.extra = stream;
    Py_XINCREF(callback); Py_INCREF(stream);
    cb.state = PyEval_SaveThread();
    ret = LIBMTP_Get_File_To_Handler(self->device, (uint32_t)fileid, data_to_python, &cb, report_progress, &cb);
    PyEval_RestoreThread(cb.state);
    Py_XDECREF(callback); Py_DECREF(stream);

    if (ret != 0) { 
        dump_errorstack(self->device, errs);
    }
    Py_XDECREF(PyObject_CallMethod(stream, "flush", NULL));
    return Py_BuildValue("ON", (ret == 0) ? Py_True : Py_False, errs);

} // }}}
Exemple #19
0
void init_python(int argc, char** argv) {
  Py_Initialize();

  PySys_SetArgvEx(argc, argv, 0);

  set_gl_sys_path();

  PyEval_InitThreads();
  PyEval_SaveThread(); // release the GIL

  {
    python_thread_guard py_thread_guard;
    try {
      gl = boost::python::import("graphlab");
      image_class = python::import("graphlab.data_structures.image").attr("Image");
      gc = python::import("gc");
    } catch (python::error_already_set const& e) {
      std::string error_string = parse_python_error();
      std::cerr << error_string << std::endl;
      throw(error_string);
    } catch (...) {
      throw(std::string("Unknown error when import graphlab"));
    }
  }
}
Exemple #20
0
// Device.put_file {{{
static PyObject *
Device_put_file(Device *self, PyObject *args) {
    PyObject *stream, *callback = NULL, *errs, *fo = NULL;
    ProgressCallback cb;
    unsigned long parent_id, storage_id;
    unsigned long long filesize;
    int ret;
    char *name;
    LIBMTP_file_t f;

    ENSURE_DEV(NULL); ENSURE_STORAGE(NULL);

    if (!PyArg_ParseTuple(args, "kksOK|O", &storage_id, &parent_id, &name, &stream, &filesize, &callback)) return NULL; 
    errs = PyList_New(0);
    if (errs == NULL) { PyErr_NoMemory(); return NULL; }
    if (callback == NULL || !PyCallable_Check(callback)) callback = NULL;

    cb.obj = callback; cb.extra = stream;
    f.parent_id = (uint32_t)parent_id; f.storage_id = (uint32_t)storage_id; f.item_id = 0; f.filename = name; f.filetype = LIBMTP_FILETYPE_UNKNOWN; f.filesize = (uint64_t)filesize;
    Py_XINCREF(callback); Py_INCREF(stream);
    cb.state = PyEval_SaveThread();
    ret = LIBMTP_Send_File_From_Handler(self->device, data_from_python, &cb, &f, report_progress, &cb);
    PyEval_RestoreThread(cb.state);
    Py_XDECREF(callback); Py_DECREF(stream);

    if (ret != 0) dump_errorstack(self->device, errs);
    else fo = file_metadata(self->device, errs, f.item_id, storage_id);
    if (fo == NULL) { fo = Py_None; Py_INCREF(fo); }

    return Py_BuildValue("NN", fo, errs);

} // }}}
PyObject *
py_guestfs_close (PyObject *self, PyObject *args)
{
  PyThreadState *py_save = NULL;
  PyObject *py_g;
  guestfs_h *g;
  size_t i, len;
  PyObject **callbacks;

  if (!PyArg_ParseTuple (args, (char *) "O:guestfs_close", &py_g))
    return NULL;
  g = get_handle (py_g);

  /* As in the OCaml bindings, there is a hard to solve case where the
   * caller can delete a callback from within the callback, resulting
   * in a double-free here.  XXX
   */
  callbacks = get_all_event_callbacks (g, &len);

  if (PyEval_ThreadsInitialized ())
    py_save = PyEval_SaveThread ();
  guestfs_close (g);
  if (PyEval_ThreadsInitialized ())
    PyEval_RestoreThread (py_save);

  for (i = 0; i < len; ++i)
    Py_XDECREF (callbacks[i]);
  free (callbacks);

  Py_INCREF (Py_None);
  return Py_None;
}
Exemple #22
0
void AllowThreads(PCRITICAL_SECTION cs, std::function<void()> action)
{
    PyThreadState* _save = nullptr;
    try
    {
        // Py_BEGIN_ALLOW_THREADS
        _save = PyEval_SaveThread();
        if (cs)
        {
            ::EnterCriticalSection(cs);
        }

        action();

        if (cs)
        {
            ::LeaveCriticalSection(cs);
        }
        // Py_END_ALLOW_THREADS
        PyEval_RestoreThread(_save);
    }
    catch (std::exception&)
    {
        if (cs)
        {
            ::LeaveCriticalSection(cs);
        }
        if (_save)
        {
            PyEval_RestoreThread(_save);
        }
        throw;
    }
}
Exemple #23
0
void embed_init_python(void)
{
    FENTER;

#ifndef PYTHON_SO_LIB
#error "Python version needs passing in with -DPYTHON_SO_VERSION=libpython<ver>.so"
#else
#define PY_SO_LIB xstr(PYTHON_SO_LIB)
#endif

    void *ret = dlopen(PY_SO_LIB, RTLD_LAZY | RTLD_GLOBAL);
    if (!ret) {
        fprintf(stderr, "Failed to find python lib %s (%s)\n", PY_SO_LIB, dlerror());
    }

    // Don't initialise python if already running
    if (gtstate)
        return;

    Py_SetProgramName(progname);
    Py_Initialize();                    /* Initialize the interpreter */
    PySys_SetArgvEx(1, argv, 0);
    PyEval_InitThreads();               /* Create (and acquire) the interpreter lock */

    /* Swap out and return current thread state and release the GIL */
    gtstate = PyEval_SaveThread();
    FEXIT;
}
void PyXPCOM_DLLAddRef(void)
{
	// Must be thread-safe, although cant have the Python lock!
	CEnterLeaveXPCOMFramework _celf;
	PRInt32 cnt = PR_AtomicIncrement(&g_cLockCount);
	if (cnt==1) { // First call
		if (!Py_IsInitialized()) {
			Py_Initialize();
			// Make sure our Windows framework is all setup.
			PyXPCOM_Globals_Ensure();
			// Make sure we have _something_ as sys.argv.
			if (PySys_GetObject((char*)"argv")==NULL) {
				PyObject *path = PyList_New(0);
#if PY_MAJOR_VERSION <= 2
				PyObject *str = PyString_FromString("");
#else
				PyObject *str = PyUnicode_FromString("");
#endif
				PyList_Append(path, str);
				PySys_SetObject((char*)"argv", path);
				Py_XDECREF(path);
				Py_XDECREF(str);
			}

			// Must force Python to start using thread locks, as
			// we are free-threaded (maybe, I think, sometimes :-)
			PyEval_InitThreads();
#ifndef PYXPCOM_USE_PYGILSTATE
			// Release Python lock, as first thing we do is re-get it.
			ptsGlobal = PyEval_SaveThread();
#endif
			// NOTE: We never finalize Python!!
		}
	}
}
Exemple #25
0
static PyObject *
rpmts_Check(rpmtsObject * s, PyObject * args, PyObject * kwds)
{
    struct rpmtsCallbackType_s cbInfo;
    int rc;
    char * kwlist[] = {"callback", NULL};

    memset(&cbInfo, 0, sizeof(cbInfo));
    if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:Check", kwlist,
	    &cbInfo.cb))
	return NULL;

    if (cbInfo.cb != NULL) {
	if (!PyCallable_Check(cbInfo.cb)) {
	    PyErr_SetString(PyExc_TypeError, "expected a callable");
	    return NULL;
	}
	rc = rpmtsSetSolveCallback(s->ts, rpmts_SolveCallback, (void *)&cbInfo);
    }

    cbInfo.tso = s;
    cbInfo._save = PyEval_SaveThread();

    rc = rpmtsCheck(s->ts);

    PyEval_RestoreThread(cbInfo._save);

    return PyBool_FromLong((rc == 0));
}
Exemple #26
0
static char *
on_completion(char *text, int state)
{
	char *result = NULL;
	if (completer != NULL) {
		PyObject *r;
		PyThreadState *save_tstate;
		/* Note that readline is called with the interpreter
		   lock released! */
		save_tstate = PyThreadState_Swap(NULL);
		PyEval_RestoreThread(tstate);
		r = PyObject_CallFunction(completer, "si", text, state);
		if (r == NULL)
			goto error;
		if (r == Py_None) {
			result = NULL;
		}
		else {
			char *s = PyString_AsString(r);
			if (s == NULL)
				goto error;
			result = strdup(s);
		}
		Py_DECREF(r);
		goto done;
	  error:
		PyErr_Clear();
		Py_XDECREF(r);
	  done:
		PyEval_SaveThread();
		PyThreadState_Swap(save_tstate);
	}
	return result;
}
Exemple #27
0
static PyObject *
rpmts_Run(rpmtsObject * s, PyObject * args, PyObject * kwds)
{
    int rc;
    struct rpmtsCallbackType_s cbInfo;
    rpmprobFilterFlags ignoreSet;
    char * kwlist[] = {"callback", "data", "ignoreSet", NULL};

    if (!PyArg_ParseTupleAndKeywords(args, kwds, "OOi:Run", kwlist,
	    &cbInfo.cb, &cbInfo.data, &ignoreSet))
	return NULL;

    cbInfo.tso = s;
    cbInfo._save = PyEval_SaveThread();

    if (cbInfo.cb != NULL) {
	if (!PyCallable_Check(cbInfo.cb)) {
	    PyErr_SetString(PyExc_TypeError, "expected a callable");
	    return NULL;
	}
	(void) rpmtsSetNotifyCallback(s->ts, rpmtsCallback, (void *) &cbInfo);
    }

    rc = rpmtsRun(s->ts, NULL, ignoreSet);

    if (cbInfo.cb)
	(void) rpmtsSetNotifyCallback(s->ts, NULL, NULL);

    PyEval_RestoreThread(cbInfo._save);

    return Py_BuildValue("i", rc);
}
Exemple #28
0
/* rle_decode(byte_array, lbrow, lbnpt, mdi) */
static PyObject *rle_decode_py(PyObject *self, PyObject *args)
{
    char *bytes_in=NULL;
    PyArrayObject *npy_array_out=NULL;
    int bytes_in_len;
    npy_intp dims[2];
    int lbrow, lbnpt, npts;
    float mdi;

    if (!PyArg_ParseTuple(args, "s#iif", &bytes_in, &bytes_in_len, &lbrow, &lbnpt, &mdi)) return NULL;

    // Unpacking algorithm accepts an int - so assert that lbrow*lbnpt does not overflow
    if (lbrow > 0 && lbnpt >= INT_MAX / (lbrow+1)) {
        PyErr_SetString(PyExc_ValueError, "Resulting unpacked PP field is larger than PP supports.");
        return NULL;
    } else {
        npts = lbnpt*lbrow;
    }

    // We can't use the macros Py_BEGIN_ALLOW_THREADS / Py_END_ALLOW_THREADS
    // because they declare a new scope block, but we want multiple exits.
    PyThreadState *_save;
    _save = PyEval_SaveThread();

    float *dataout = (float*)calloc(npts, sizeof(float));

    if (dataout == NULL) {
        PyEval_RestoreThread(_save);
        PyErr_SetString(PyExc_ValueError, "Unable to allocate memory for wgdos_unpacking.");
        return NULL;
    }

    function func;  // function is defined by wgdosstuff.
    set_function_name(__func__, &func, 0);
    int status = unpack_ppfield(mdi, (bytes_in_len/BYTES_PER_INT_UNPACK_PPFIELD), bytes_in, LBPACK_RLE_PACKED, npts, dataout, &func);

    /* Raise an exception if there was a problem with the REL algorithm */
    if (status != 0) {
        free(dataout);
        PyEval_RestoreThread(_save);
        PyErr_SetString(PyExc_ValueError, "RLE decode encountered an error.");
        return NULL;
    }
    else {
        /* The data came back fine, so make a Numpy array and return it */
        dims[0]=lbrow;
        dims[1]=lbnpt;
        PyEval_RestoreThread(_save);
        npy_array_out=(PyArrayObject *) PyArray_SimpleNewFromData(2, dims, NPY_FLOAT, dataout);

        if (npy_array_out == NULL) {
            PyErr_SetString(PyExc_ValueError, "Failed to make the numpy array for the packed data.");
            return NULL;
        }

        // give ownership of dataout to the Numpy array - Numpy will then deal with memory cleanup.
        npy_array_out->flags = npy_array_out->flags | NPY_OWNDATA;
        return (PyObject *)npy_array_out;
    }
}
Exemple #29
0
static PyObject *
pylcm_handle (PyLCMObject *lcm_obj)
{
    dbg(DBG_PYTHON, "pylcm_handle(%p)\n", lcm_obj);

    if (lcm_obj->saved_thread_state) {
        PyErr_SetString (PyExc_RuntimeError,
            "only one thread is allowed to call LCM.handle() or LCM.handle_timeout() at a time");
        return NULL;
    }
    lcm_obj->saved_thread_state = PyEval_SaveThread();
    lcm_obj->exception_raised = 0;

    dbg(DBG_PYTHON, "calling lcm_handle(%p)\n", lcm_obj->lcm);
    int status = lcm_handle (lcm_obj->lcm);

    // Restore the thread state before returning back to Python.  The thread
    // state may have already been restored by the callback function
    // pylcm_msg_handler()
    if (lcm_obj->saved_thread_state) {
      PyEval_RestoreThread(lcm_obj->saved_thread_state);
      lcm_obj->saved_thread_state = NULL;
    }

    if (lcm_obj->exception_raised) { return NULL; }
    if (status < 0) {
        PyErr_SetString (PyExc_IOError, "lcm_handle() returned -1");
        return NULL;
    }
    Py_RETURN_NONE;
}
	void PythonModule::Initialize()
	{
		PythonModule::instance_ = this;

		Py_Initialize();
		PyEval_InitThreads();
		PyEval_SaveThread();

		{
			PyLockGIL lock;

			PyObject* path = PySys_GetObject((char*) "path");
			PyListInsertString(path, 0, 
				UTF8ToSystem(host->GetApplication()->GetResourcesPath()).c_str());
#ifdef OS_WIN32
			PyListInsertString(path, 0, FileUtils::Join(
				UTF8ToSystem(this->GetPath()).c_str(), "DLLs", NULL));
			PyListInsertString(path, 0, FileUtils::Join(
				UTF8ToSystem(this->GetPath()).c_str(), "Lib", NULL));
			PyListInsertString(path, 0, FileUtils::Join(
				UTF8ToSystem(this->GetPath()).c_str(), "Lib", "lib-tk", NULL));
#endif
		}

        host->script()->AddInterpreter(&interpreter, supportedScriptTypes);

		PythonUtils::InitializePythonKClasses();
		host->AddModuleProvider(this);
	}