コード例 #1
0
ファイル: threadmodule.c プロジェクト: Vignesh2736/IncPy
static void
local_dealloc(localobject *self)
{
	PyThreadState *tstate;
	if (self->key
	    && (tstate = PyThreadState_Get())
	    && tstate->interp) {
		for(tstate = PyInterpreterState_ThreadHead(tstate->interp);
		    tstate;
		    tstate = PyThreadState_Next(tstate)) 
			if (tstate->dict &&
			    PyDict_GetItem(tstate->dict, self->key))
				PyDict_DelItem(tstate->dict, self->key);
	}

	Py_XDECREF(self->key);
	local_clear(self);
	Py_TYPE(self)->tp_free((PyObject*)self);
}
コード例 #2
0
ファイル: psycopgmodule.c プロジェクト: LauraJUK/For-The-Vin
/* Return nonzero if the current one is the main interpreter */
static int
psyco_is_main_interp(void)
{
    static PyInterpreterState *main_interp = NULL;  /* Cached reference */
    PyInterpreterState *interp;

    if (main_interp) {
        return (main_interp == PyThreadState_Get()->interp);
    }

    /* No cached value: cache the proper value and try again. */
    interp = PyInterpreterState_Head();
    while (interp->next)
        interp = interp->next;

    main_interp = interp;
    assert (main_interp);
    return psyco_is_main_interp();
}
コード例 #3
0
void clPyGlueInit(char* appModule,void (*init_extensions[])(void),int argc, char**argv)
{
  char buf[1024];
  ClRcT rc;
    Py_Initialize();
    PySys_SetArgv(argc, argv);
    PyEval_InitThreads();
    
    if (init_extensions) 
      {
        int i = 0;
        for(i=0; init_extensions[i]!=NULL; i++) (*init_extensions[i])();
      }
    thrdState = PyThreadState_Get();

    rc = clOsalMutexInit(&pyMutex);
    CL_ASSERT(rc==CL_OK); 

    rc = clOsalCondInit(&event);
    CL_ASSERT(rc==CL_OK); 

    rc = clOsalMutexLock(&pyMutex);
    CL_ASSERT(rc==CL_OK); 

    PyThreadState_Swap(thrdState);

    PyRun_SimpleString("import os, os.path, sys\n");
    snprintf(buf,1024,"sys.path.append(os.path.realpath('%s'))\n",CL_APP_BINDIR);
    clprintf(CL_LOG_SEV_INFO, buf);
    PyRun_SimpleString(buf);
    //PyRun_SimpleString("sys.path.append(os.path.realpath('../../bin'))\n");
    snprintf(buf,1024,"from %s import *\n",appModule);
    clprintf(CL_LOG_SEV_INFO, buf);
    PyRun_SimpleString(buf);

    PyThreadState_Swap(NULL);
    PyEval_ReleaseLock();

    rc=clOsalMutexUnlock(&pyMutex);
    CL_ASSERT(rc==CL_OK); 

}
コード例 #4
0
ファイル: faulthandler.c プロジェクト: Naddiseo/cpython
static void
faulthandler_user(int signum)
{
    user_signal_t *user;
    PyThreadState *tstate;
    int save_errno = errno;

    user = &user_signals[signum];
    if (!user->enabled)
        return;

#ifdef WITH_THREAD
    /* PyThreadState_Get() doesn't give the state of the current thread if
       the thread doesn't hold the GIL. Read the thread local storage (TLS)
       instead: call PyGILState_GetThisThreadState(). */
    tstate = PyGILState_GetThisThreadState();
#else
    tstate = PyThreadState_Get();
#endif

    if (user->all_threads)
        _Py_DumpTracebackThreads(user->fd, user->interp, tstate);
    else {
        if (tstate == NULL)
            return;
        _Py_DumpTraceback(user->fd, tstate);
    }
#ifdef HAVE_SIGACTION
    if (user->chain) {
        (void)sigaction(signum, &user->previous, NULL);
        /* call the previous signal handler */
        raise(signum);
        (void)faulthandler_register(signum, user->chain, NULL);
    }
#else
    if (user->chain) {
        /* call the previous signal handler */
        user->previous(signum);
    }
#endif
    errno = save_errno;
}
コード例 #5
0
static void clRunPython(char* cmd)
{ 
  #define BSZ 2048
  char pyBuf[BSZ];
  clprintf (CL_LOG_SEV_INFO, "clRunPython called with [%s]", cmd);
  //clOsalMutexLock(&pyMutex);
  thrdState = PyThreadState_Get();
  
  #if 0
  if (quit)
    {
      clprintf(CL_LOG_SEV_INFO,"Python has quit, so not running: %s",cmd);
      //clOsalMutexUnlock(&pyMutex);
      return;
    }
  #endif

#if 0
  PyEval_AcquireLock();
  PyThreadState_Swap(thrdState);
#endif

  snprintf(pyBuf,BSZ,"clCmdFromAsp(\"\"\"%s\"\"\")\n",cmd);

  clprintf (CL_LOG_SEV_INFO, "clRunPython requesting python lock [%s]", cmd);
  PyEval_AcquireThread(thrdState);
  clprintf(CL_LOG_SEV_INFO,"Stage 1.  Passing to Python layer: %s",pyBuf);
  int ret = PyRun_SimpleString(pyBuf);
  clprintf (CL_LOG_SEV_INFO, "clRunPython requesting release of python lock [%s]", cmd);
  PyEval_ReleaseThread(thrdState);

  if (ret != 0)  clprintf(CL_LOG_SEV_ERROR,"Ran: %s.  There was an error.",pyBuf);

#if 0
  PyThreadState_Swap(NULL);
  PyEval_ReleaseLock();
#endif

  //clprintf (CL_LOG_SEV_INFO, "clRunPython unlocking mutex [%s]", cmd);
  //clOsalMutexUnlock(&pyMutex);
  //clprintf (CL_LOG_SEV_INFO, "clRunPython unlocked mutex [%s]", cmd);
}
コード例 #6
0
ファイル: monitor.cpp プロジェクト: Ayu222/android
  PyObject* Monitor_New(PyTypeObject *type, PyObject *args, PyObject *kwds)
  {
    Monitor *self;

    self = (Monitor*)type->tp_alloc(type, 0);
    if (!self) return NULL;
    std::string addonId;
    if (!PyXBMCGetAddonId(addonId) || addonId.empty())
    {
      PyErr_SetString((PyObject*)self, "Unable to identify addon");
      return NULL;
    }    
    CPyThreadState pyState;
    self->pMonitor = new CPythonMonitor();
    pyState.Restore();
    self->pMonitor->Id = addonId;    
    self->pMonitor->SetCallback(PyThreadState_Get(), (PyObject*)self);
 
    return (PyObject*)self;
  }
コード例 #7
0
ファイル: callbacks.c プロジェクト: GuardianRG/static-python
/* after code that pyrex generates */
void _ctypes_add_traceback(char *funcname, char *filename, int lineno)
{
    PyObject *py_globals = 0;
    PyCodeObject *py_code = 0;
    PyFrameObject *py_frame = 0;
    PyObject *exception, *value, *tb;

    /* (Save and) Clear the current exception. Python functions must not be
       called with an exception set. Calling Python functions happens when
       the codec of the filesystem encoding is implemented in pure Python. */
    PyErr_Fetch(&exception, &value, &tb);

    py_globals = PyDict_New();
    if (!py_globals)
        goto bad;
    py_code = PyCode_NewEmpty(filename, funcname, lineno);
    if (!py_code)
        goto bad;
    py_frame = PyFrame_New(
        PyThreadState_Get(), /*PyThreadState *tstate,*/
        py_code,             /*PyCodeObject *code,*/
        py_globals,          /*PyObject *globals,*/
        0                    /*PyObject *locals*/
        );
    if (!py_frame)
        goto bad;
    py_frame->f_lineno = lineno;

    PyErr_Restore(exception, value, tb);
    PyTraceBack_Here(py_frame);

    Py_DECREF(py_globals);
    Py_DECREF(py_code);
    Py_DECREF(py_frame);
    return;

  bad:
    Py_XDECREF(py_globals);
    Py_XDECREF(py_code);
    Py_XDECREF(py_frame);
}
コード例 #8
0
ファイル: stats.c プロジェクト: Galland/nodebox-opengl
DEFINEFN
void psyco_stats_reset(void)
{
	/* reset all stats */
	int i = 0;
	PyObject *key, *value, *d;
	stats_printf(("stats: reset\n"));

	/* reset the charge of all PyCodeStats, keep only the used ones */
        RECLIMIT_SAFE_ENTER();
	d = PyDict_New();
	if (d == NULL)
		OUT_OF_MEMORY();
	while (PyDict_Next(codestats_dict, &i, &key, &value)) {
		PyCodeStats* cs = (PyCodeStats*) key;
		if (cs->st_mergepoints) {
			/* clear the charge and keep alive */
			cs->st_charge = 0.0f;
			if (PyDict_SetItem(d, key, value))
				OUT_OF_MEMORY();
		}
	}
        RECLIMIT_SAFE_LEAVE();
	Py_DECREF(codestats_dict);
	codestats_dict = d;
	charge_total = 0.0;
	charge_prelimit = 0.0f;

	/* reset the time measure in all threads */
	{
#if MEASURE_ALL_THREADS
		PyInterpreterState* istate = PyThreadState_Get()->interp;
		PyThreadState* tstate;
		for (tstate=istate->tstate_head; tstate; tstate=tstate->next) {
			(void) get_measure(tstate);
		}
#else
		(void) get_measure(NULL);
#endif
	}
}
コード例 #9
0
ファイル: pythonrun.c プロジェクト: MatiasNAmendola/cleese
void
Py_Finalize(void)
{
    LOG("> Py_Finalize\n"); {
    PyInterpreterState *interp;
    PyThreadState *tstate;
    
    initialized = 0;
    
    tstate = PyThreadState_Get();
    interp = tstate->interp;
    
    PyInterpreterState_Clear(interp);
    
    PyThreadState_Swap(NULL);
    PyInterpreterState_Delete(interp);
    
    PyFrame_Fini();
    PyInt_Fini();
    LOG("< Py_Finalize\n");
}}
コード例 #10
0
ファイル: rtmidimodule.cpp プロジェクト: DerThorsten/pyrtmidi
static PyObject *
MidiIn_openPort(MidiIn *self, PyObject *args)
{
  int port;
  char *name = NULL;

  if(!PyArg_ParseTuple(args, "i|s", &port, &name))
    return NULL;

  if (name == NULL)
  {
    try
    {
      self->rtmidi->openPort(port);
    }
    catch(RtError &error)
    {
      PyErr_SetString(RtMidiError, error.getMessageString());
      return NULL;
    }
  }

  else
  {
    try
    {
      self->rtmidi->openPort(port,name);
    }
    catch(RtError &error)
    {
      PyErr_SetString(RtMidiError, error.getMessageString());
      return NULL;
    }
  }

  self->rtmidi->setCallback(MidiIn_callback, self);
  self->calling_thread_id = PyThreadState_Get()->thread_id;

  Py_RETURN_NONE;
}
コード例 #11
0
ファイル: faulthandler.c プロジェクト: pombredanne/cpython
static PyObject*
faulthandler_dump_traceback_py(PyObject *self,
                               PyObject *args, PyObject *kwargs)
{
    static char *kwlist[] = {"file", "all_threads", NULL};
    PyObject *file = NULL;
    int all_threads = 0;
    PyThreadState *tstate;
    const char *errmsg;
    int fd;

    if (!PyArg_ParseTupleAndKeywords(args, kwargs,
        "|Oi:dump_traceback", kwlist,
        &file, &all_threads))
        return NULL;

    file = faulthandler_get_fileno(file, &fd);
    if (file == NULL)
        return NULL;

    /* The caller holds the GIL and so PyThreadState_Get() can be used */
    tstate = PyThreadState_Get();
    if (tstate == NULL) {
        PyErr_SetString(PyExc_RuntimeError,
                        "unable to get the current thread state");
        return NULL;
    }

    if (all_threads) {
        errmsg = _Py_DumpTracebackThreads(fd, tstate->interp, tstate);
        if (errmsg != NULL) {
            PyErr_SetString(PyExc_RuntimeError, errmsg);
            return NULL;
        }
    }
    else {
        _Py_DumpTraceback(fd, tstate);
    }
    Py_RETURN_NONE;
}
コード例 #12
0
ファイル: codeobject.c プロジェクト: Apoorvadabhere/cpython
int
_PyCode_SetExtra(PyObject *code, Py_ssize_t index, void *extra)
{
    PyInterpreterState *interp = PyThreadState_Get()->interp;

    if (!PyCode_Check(code) || index < 0 ||
            index >= interp->co_extra_user_count) {
        PyErr_BadInternalCall();
        return -1;
    }

    PyCodeObject *o = (PyCodeObject*) code;
    _PyCodeObjectExtra *co_extra = (_PyCodeObjectExtra *) o->co_extra;

    if (co_extra == NULL || co_extra->ce_size <= index) {
        Py_ssize_t i = (co_extra == NULL ? 0 : co_extra->ce_size);
        co_extra = PyMem_Realloc(
                co_extra,
                sizeof(_PyCodeObjectExtra) +
                (interp->co_extra_user_count-1) * sizeof(void*));
        if (co_extra == NULL) {
            return -1;
        }
        for (; i < interp->co_extra_user_count; i++) {
            co_extra->ce_extras[i] = NULL;
        }
        co_extra->ce_size = interp->co_extra_user_count;
        o->co_extra = co_extra;
    }

    if (co_extra->ce_extras[index] != NULL) {
        freefunc free = interp->co_extra_freefuncs[index];
        if (free != NULL) {
            free(co_extra->ce_extras[index]);
        }
    }

    co_extra->ce_extras[index] = extra;
    return 0;
}
コード例 #13
0
ファイル: script.cpp プロジェクト: CoolJie2001/kbengine
//-------------------------------------------------------------------------------------
PyThreadState* Script::createInterpreter()
{
	PyThreadState* 	pCurInterpreter = PyThreadState_Get();
	PyObject * 		pCurPath = PySys_GetObject( "path" );

	PyThreadState* pNewInterpreter = Py_NewInterpreter();
	if (pNewInterpreter)
	{
		PySys_SetObject( "path", pCurPath );
#ifndef KBE_SINGLE_THREADED
		PyDict_Merge( PySys_GetObject( "modules" ), s_pOurInitTimeModules, 0 );
#endif

		PyThreadState* pSwapped = PyThreadState_Swap( pCurInterpreter );
		if( pSwapped != pNewInterpreter )
		{
			KBE_EXIT( "error creating new python interpreter" );
		}
	}

	return pNewInterpreter;
}
コード例 #14
0
ファイル: swig.cpp プロジェクト: CaptainRewind/xbmc
  static bool handleInterpRegistrationForClean(XBMCAddon::AddonClass* c)
  {
    XBMC_TRACE;
    if(c){
      XBMCAddon::AddonClass::Ref<XBMCAddon::Python::PythonLanguageHook> lh = 
        XBMCAddon::AddonClass::Ref<XBMCAddon::AddonClass>(c->GetLanguageHook());

      if (lh.isNotNull())
      {
        lh->UnregisterAddonClassInstance(c);
        return true;
      }
      else
      {
        PyThreadState* state = PyThreadState_Get();
        lh = XBMCAddon::Python::PythonLanguageHook::GetIfExists(state->interp);
        if (lh.isNotNull()) lh->UnregisterAddonClassInstance(c);
        return true;
      }
    }
    return false;
  }
コード例 #15
0
ファイル: Stemmer.c プロジェクト: buriy/pystemmer
static int __Pyx_GetException(PyObject **type, PyObject **value, PyObject **tb) {
    PyThreadState *tstate = PyThreadState_Get();
    PyErr_Fetch(type, value, tb);
    PyErr_NormalizeException(type, value, tb);
    if (PyErr_Occurred())
        goto bad;
    Py_INCREF(*type);
    Py_INCREF(*value);
    Py_INCREF(*tb);
    Py_XDECREF(tstate->exc_type);
    Py_XDECREF(tstate->exc_value);
    Py_XDECREF(tstate->exc_traceback);
    tstate->exc_type = *type;
    tstate->exc_value = *value;
    tstate->exc_traceback = *tb;
    return 0;
bad:
    Py_XDECREF(*type);
    Py_XDECREF(*value);
    Py_XDECREF(*tb);
    return -1;
}
コード例 #16
0
static PyObject *
MidiIn_openVirtualPort(MidiIn *self, PyObject *args)
{
  char *name = NULL;
  
  if(!PyArg_ParseTuple(args, "|s", &name))
    return NULL;
  
  if(name == NULL)
  {
    try
    {
      self->rtmidi->openVirtualPort();
    }
    catch(RtMidiError &error)
    {
      PyErr_SetString(rtmidi_Error, error.what());
      return NULL;
    }
  }
  else
  {
    try
    {
      self->rtmidi->openVirtualPort(name);
    }
    catch(RtMidiError &error)
    {
      PyErr_SetString(rtmidi_Error, error.what());
      return NULL;
    }
  }
  
  self->rtmidi->setCallback(MidiIn_callback, self);
  self->calling_thread_id = PyThreadState_Get()->thread_id;
  
  Py_RETURN_NONE;
}
コード例 #17
0
ファイル: _testembed.c プロジェクト: Orav/kbengine
static void test_repeated_init_and_subinterpreters(void)
{
    PyThreadState *mainstate, *substate;
#ifdef WITH_THREAD
    PyGILState_STATE gilstate;
#endif
    int i, j;

    for (i=0; i<3; i++) {
        printf("--- Pass %d ---\n", i);
        _testembed_Py_Initialize();
        mainstate = PyThreadState_Get();

#ifdef WITH_THREAD
        PyEval_InitThreads();
        PyEval_ReleaseThread(mainstate);

        gilstate = PyGILState_Ensure();
#endif
        print_subinterp();
        PyThreadState_Swap(NULL);

        for (j=0; j<3; j++) {
            substate = Py_NewInterpreter();
            print_subinterp();
            Py_EndInterpreter(substate);
        }

        PyThreadState_Swap(mainstate);
        print_subinterp();
#ifdef WITH_THREAD
        PyGILState_Release(gilstate);
#endif

        PyEval_RestoreThread(mainstate);
        Py_Finalize();
    }
}
コード例 #18
0
ファイル: pystate.c プロジェクト: arizvisa/cpython
void
_PyCrossInterpreterData_Release(_PyCrossInterpreterData *data)
{
    if (data->data == NULL && data->obj == NULL) {
        // Nothing to release!
        return;
    }

    // Switch to the original interpreter.
    PyInterpreterState *interp = _PyInterpreterState_LookUpID(data->interp);
    if (interp == NULL) {
        // The intepreter was already destroyed.
        if (data->free != NULL) {
            // XXX Someone leaked some memory...
        }
        return;
    }

    PyThreadState *save_tstate = NULL;
    if (interp != PyThreadState_Get()->interp) {
        // XXX Using the "head" thread isn't strictly correct.
        PyThreadState *tstate = PyInterpreterState_ThreadHead(interp);
        // XXX Possible GILState issues?
        save_tstate = PyThreadState_Swap(tstate);
    }

    // "Release" the data and/or the object.
    if (data->free != NULL) {
        data->free(data->data);
    }
    Py_XDECREF(data->obj);

    // Switch back.
    if (save_tstate != NULL) {
        PyThreadState_Swap(save_tstate);
    }
}
コード例 #19
0
ファイル: context.c プロジェクト: Apoorvadabhere/cpython
static int
contextvar_set(PyContextVar *var, PyObject *val)
{
    var->var_cached = NULL;
    PyThreadState *ts = PyThreadState_Get();

    PyContext *ctx = context_get();
    if (ctx == NULL) {
        return -1;
    }

    PyHamtObject *new_vars = _PyHamt_Assoc(
        ctx->ctx_vars, (PyObject *)var, val);
    if (new_vars == NULL) {
        return -1;
    }

    Py_SETREF(ctx->ctx_vars, new_vars);

    var->var_cached = val;  /* borrow */
    var->var_cached_tsid = ts->id;
    var->var_cached_tsver = ts->context_ver;
    return 0;
}
コード例 #20
0
ファイル: libkvipythoncore.cpp プロジェクト: kartagis/KVIrc
static bool pythoncore_module_init(KviModule *)
{
#ifdef COMPILE_PYTHON_SUPPORT

	// Initialize the Python interpreter
	Py_Initialize();
	PyEval_InitThreads();

	// save a pointer to the main PyThreadState object
	mainThreadState = PyThreadState_Get();
	// release the lock
	PyEval_ReleaseLock();

	// Initialize the Python module for KVIrc
	python_init();

	g_pInterpreters = new KviPointerHashTable<QString,KviPythonInterpreter>(17,false);
	g_pInterpreters->setAutoDelete(false);
	return true;

#endif // COMPILE_PYTHON_SUPPORT

	return false;
}
コード例 #21
0
ファイル: callbacks.c プロジェクト: 469306621/Languages
/* after code that pyrex generates */
void _ctypes_add_traceback(char *funcname, char *filename, int lineno)
{
    PyObject *py_globals = 0;
    PyCodeObject *py_code = 0;
    PyFrameObject *py_frame = 0;

    py_globals = PyDict_New();
    if (!py_globals) goto bad;
    py_code = PyCode_NewEmpty(filename, funcname, lineno);
    if (!py_code) goto bad;
    py_frame = PyFrame_New(
        PyThreadState_Get(), /*PyThreadState *tstate,*/
        py_code,             /*PyCodeObject *code,*/
        py_globals,          /*PyObject *globals,*/
        0                    /*PyObject *locals*/
        );
    if (!py_frame) goto bad;
    py_frame->f_lineno = lineno;
    PyTraceBack_Here(py_frame);
  bad:
    Py_XDECREF(py_globals);
    Py_XDECREF(py_code);
    Py_XDECREF(py_frame);
}
コード例 #22
0
ファイル: faulthandler.c プロジェクト: mikegraham/cpython
static void
faulthandler_fatal_error(int signum)
{
    const int fd = fatal_error.fd;
    unsigned int i;
    fault_handler_t *handler = NULL;
    PyThreadState *tstate;
    int save_errno = errno;

    if (!fatal_error.enabled)
        return;

    for (i=0; i < faulthandler_nsignals; i++) {
        handler = &faulthandler_handlers[i];
        if (handler->signum == signum)
            break;
    }
    if (handler == NULL) {
        /* faulthandler_nsignals == 0 (unlikely) */
        return;
    }

    /* restore the previous handler */
#ifdef HAVE_SIGACTION
    (void)sigaction(signum, &handler->previous, NULL);
#else
    (void)signal(signum, handler->previous);
#endif
    handler->enabled = 0;

    PUTS(fd, "Fatal Python error: ");
    PUTS(fd, handler->name);
    PUTS(fd, "\n\n");

#ifdef WITH_THREAD
    /* SIGSEGV, SIGFPE, SIGABRT, SIGBUS and SIGILL are synchronous signals and
       are thus delivered to the thread that caused the fault. Get the Python
       thread state of the current thread.

       PyThreadState_Get() doesn't give the state of the thread that caused the
       fault if the thread released the GIL, and so this function cannot be
       used. Read the thread local storage (TLS) instead: call
       PyGILState_GetThisThreadState(). */
    tstate = PyGILState_GetThisThreadState();
#else
    tstate = PyThreadState_Get();
#endif

    if (fatal_error.all_threads)
        _Py_DumpTracebackThreads(fd, fatal_error.interp, tstate);
    else {
        if (tstate != NULL)
            _Py_DumpTraceback(fd, tstate);
    }

    errno = save_errno;
#ifdef MS_WINDOWS
    if (signum == SIGSEGV) {
        /* don't explicitly call the previous handler for SIGSEGV in this signal
           handler, because the Windows signal handler would not be called */
        return;
    }
#endif
    /* call the previous signal handler: it is called immediatly if we use
       sigaction() thanks to SA_NODEFER flag, otherwise it is deferred */
    raise(signum);
}
コード例 #23
0
ファイル: _warnings.c プロジェクト: PiJoules/cpython-modified
/* Returns 0 on error (no new refs), 1 on success */
static int
setup_context(Py_ssize_t stack_level, PyObject **filename, int *lineno,
              PyObject **module, PyObject **registry)
{
    PyObject *globals;

    /* Setup globals and lineno. */
    PyFrameObject *f = PyThreadState_GET()->frame;
    // Stack level comparisons to Python code is off by one as there is no
    // warnings-related stack level to avoid.
    if (stack_level <= 0 || is_internal_frame(f)) {
        while (--stack_level > 0 && f != NULL) {
            f = f->f_back;
        }
    }
    else {
        while (--stack_level > 0 && f != NULL) {
            f = next_external_frame(f);
        }
    }

    if (f == NULL) {
        globals = PyThreadState_Get()->interp->sysdict;
        *lineno = 1;
    }
    else {
        globals = f->f_globals;
        *lineno = PyFrame_GetLineNumber(f);
    }

    *module = NULL;

    /* Setup registry. */
    assert(globals != NULL);
    assert(PyDict_Check(globals));
    *registry = PyDict_GetItemString(globals, "__warningregistry__");
    if (*registry == NULL) {
        int rc;

        *registry = PyDict_New();
        if (*registry == NULL)
            return 0;

         rc = PyDict_SetItemString(globals, "__warningregistry__", *registry);
         if (rc < 0)
            goto handle_error;
    }
    else
        Py_INCREF(*registry);

    /* Setup module. */
    *module = PyDict_GetItemString(globals, "__name__");
    if (*module == NULL) {
        *module = PyUnicode_FromString("<string>");
        if (*module == NULL)
            goto handle_error;
    }
    else
        Py_INCREF(*module);

    /* Setup filename. */
    *filename = PyDict_GetItemString(globals, "__file__");
    if (*filename != NULL && PyUnicode_Check(*filename)) {
        Py_ssize_t len;
        int kind;
        void *data;

        if (PyUnicode_READY(*filename))
            goto handle_error;

        len = PyUnicode_GetLength(*filename);
        kind = PyUnicode_KIND(*filename);
        data = PyUnicode_DATA(*filename);

#define ascii_lower(c) ((c <= 127) ? Py_TOLOWER(c) : 0)
        /* if filename.lower().endswith(".pyc"): */
        if (len >= 4 &&
            PyUnicode_READ(kind, data, len-4) == '.' &&
            ascii_lower(PyUnicode_READ(kind, data, len-3)) == 'p' &&
            ascii_lower(PyUnicode_READ(kind, data, len-2)) == 'y' &&
            ascii_lower(PyUnicode_READ(kind, data, len-1)) == 'c')
        {
            *filename = PyUnicode_Substring(*filename, 0,
                                            PyUnicode_GET_LENGTH(*filename)-1);
            if (*filename == NULL)
                goto handle_error;
        }
        else
            Py_INCREF(*filename);
    }
    else {
        *filename = NULL;
        if (*module != Py_None && PyUnicode_CompareWithASCIIString(*module, "__main__") == 0) {
            PyObject *argv = _PySys_GetObjectId(&PyId_argv);
            /* PyList_Check() is needed because sys.argv is set to None during
               Python finalization */
            if (argv != NULL && PyList_Check(argv) && PyList_Size(argv) > 0) {
                int is_true;
                *filename = PyList_GetItem(argv, 0);
                Py_INCREF(*filename);
                /* If sys.argv[0] is false, then use '__main__'. */
                is_true = PyObject_IsTrue(*filename);
                if (is_true < 0) {
                    Py_DECREF(*filename);
                    goto handle_error;
                }
                else if (!is_true) {
                    Py_XSETREF(*filename, PyUnicode_FromString("__main__"));
                    if (*filename == NULL)
                        goto handle_error;
                }
            }
            else {
                /* embedded interpreters don't have sys.argv, see bug #839151 */
                *filename = PyUnicode_FromString("__main__");
                if (*filename == NULL)
                    goto handle_error;
            }
        }
        if (*filename == NULL) {
            *filename = *module;
            Py_INCREF(*filename);
        }
    }

    return 1;

 handle_error:
    /* filename not XDECREF'ed here as there is no way to jump here with a
       dangling reference. */
    Py_XDECREF(*registry);
    Py_XDECREF(*module);
    return 0;
}
コード例 #24
0
ファイル: XBPython.cpp プロジェクト: Saddamisalami/xbmc
/**
* Should be called before executing a script
*/
void XBPython::Initialize()
{
  CLog::Log(LOGINFO, "initializing python engine. ");
  CSingleLock lock(m_critSection);
  m_iDllScriptCounter++;
  if (!m_bInitialized)
  {
      // first we check if all necessary files are installed
#ifndef _LINUX
      if(!FileExist("special://xbmc/system/python/DLLs/_socket.pyd") ||
        !FileExist("special://xbmc/system/python/DLLs/_ssl.pyd") ||
        !FileExist("special://xbmc/system/python/DLLs/bz2.pyd") ||
        !FileExist("special://xbmc/system/python/DLLs/pyexpat.pyd") ||
        !FileExist("special://xbmc/system/python/DLLs/select.pyd") ||
        !FileExist("special://xbmc/system/python/DLLs/unicodedata.pyd"))
      {
        CLog::Log(LOGERROR, "Python: Missing files, unable to execute script");
        Finalize();
        return;
      }
#endif


      // Info about interesting python envvars available
      // at http://docs.python.org/using/cmdline.html#environment-variables

#if !defined(_WIN32)
      /* PYTHONOPTIMIZE is set off intentionally when using external Python.
         Reason for this is because we cannot be sure what version of Python
         was used to compile the various Python object files (i.e. .pyo,
         .pyc, etc.). */
        // check if we are running as real xbmc.app or just binary
      if (!CUtil::GetFrameworksPath(true).IsEmpty())
      {
        // using external python, it's build looking for xxx/lib/python2.6
        // so point it to frameworks which is where python2.6 is located
        setenv("PYTHONHOME", _P("special://frameworks").c_str(), 1);
        setenv("PYTHONPATH", _P("special://frameworks").c_str(), 1);
        CLog::Log(LOGDEBUG, "PYTHONHOME -> %s", _P("special://frameworks").c_str());
        CLog::Log(LOGDEBUG, "PYTHONPATH -> %s", _P("special://frameworks").c_str());
      }
      setenv("PYTHONCASEOK", "1", 1); //This line should really be removed
#elif defined(_WIN32)
      // because the third party build of python is compiled with vs2008 we need
      // a hack to set the PYTHONPATH
      // buf is corrupted after putenv and might need a strdup but it seems to
      // work this way
      CStdString buf;
      buf = "PYTHONPATH=" + _P("special://xbmc/system/python/DLLs") + ";" + _P("special://xbmc/system/python/Lib");
      pgwin32_putenv(buf.c_str());
      buf = "PYTHONOPTIMIZE=1";
      pgwin32_putenv(buf.c_str());
      buf = "PYTHONHOME=" + _P("special://xbmc/system/python");
      pgwin32_putenv(buf.c_str());
      buf = "OS=win32";
      pgwin32_putenv(buf.c_str());

#endif

      if (PyEval_ThreadsInitialized())
        PyEval_AcquireLock();
      else
        PyEval_InitThreads();

      Py_Initialize();
      PyEval_ReleaseLock();

      // If this is not the first time we initialize Python, the interpreter
      // lock already exists and we need to lock it as PyEval_InitThreads
      // would not do that in that case.
      PyEval_AcquireLock();
      char* python_argv[1] = { (char*)"" } ;
      PySys_SetArgv(1, python_argv);

      InitXBMCTypes();
      InitGUITypes();
      InitPluginTypes();
      InitAddonTypes();

      if (!(m_mainThreadState = PyThreadState_Get()))
        CLog::Log(LOGERROR, "Python threadstate is NULL.");
      PyEval_ReleaseLock();

      m_bInitialized = true;
  }
}
コード例 #25
0
ファイル: CallbackHandler.cpp プロジェクト: A600/xbmc
 /**
  * Now we are answering the question as to whether or not we are in the
  *  PyThreadState that we were in when we started.
  */
 bool PythonCallbackHandler::isThreadStateOk()
 {
   TRACE;
   return objectThreadState == PyThreadState_Get();
 }
コード例 #26
0
ファイル: CallbackHandler.cpp プロジェクト: A600/xbmc
 /**
  * We are ASS-U-MEing that this construction is happening
  *  within the context of a Python call. This way we can
  *  store off the PyThreadState to later verify that we're
  *  handling callbacks in the appropriate thread.
  */
 PythonCallbackHandler::PythonCallbackHandler() : RetardedAsynchCallbackHandler("PythonCallbackHandler")
 {
   objectThreadState = PyThreadState_Get();
   CLog::Log(LOGDEBUG,"NEWADDON PythonCallbackHandler construction with PyThreadState 0x%lx",(long)objectThreadState);
 }
コード例 #27
0
void
Py_Finalize(void)
{
	PyInterpreterState *interp;
	PyThreadState *tstate;

	if (!initialized)
		return;
	initialized = 0;

	call_sys_exitfunc();

	/* Get current thread state and interpreter pointer */
	tstate = PyThreadState_Get();
	interp = tstate->interp;

	/* Disable signal handling */
	PyOS_FiniInterrupts();

	/* Cleanup Unicode implementation */
	_PyUnicode_Fini();

	/* Cleanup Codec registry */
	_PyCodecRegistry_Fini();

	/* Destroy all modules */
	PyImport_Cleanup();

	/* Destroy the database used by _PyImport_{Fixup,Find}Extension */
	_PyImport_Fini();

	/* Debugging stuff */
#ifdef COUNT_ALLOCS
	dump_counts();
#endif

#ifdef Py_REF_DEBUG
	fprintf(stderr, "[%ld refs]\n", _Py_RefTotal);
#endif

#ifdef Py_TRACE_REFS
	if (
#ifdef MS_WINDOWS /* Only ask on Windows if env var set */
	    getenv("PYTHONDUMPREFS") &&
#endif /* MS_WINDOWS */
	    _Py_AskYesNo("Print left references?")) {
		_Py_PrintReferences(stderr);
	}
#endif /* Py_TRACE_REFS */

	/* Now we decref the exception classes.  After this point nothing
	   can raise an exception.  That's okay, because each Fini() method
	   below has been checked to make sure no exceptions are ever
	   raised.
	*/
	fini_exceptions();

	/* Delete current thread */
	PyInterpreterState_Clear(interp);
	PyThreadState_Swap(NULL);
	PyInterpreterState_Delete(interp);

	PyMethod_Fini();
	PyFrame_Fini();
	PyCFunction_Fini();
	PyTuple_Fini();
	PyString_Fini();
	PyInt_Fini();
	PyFloat_Fini();

	/* XXX Still allocated:
	   - various static ad-hoc pointers to interned strings
	   - int and float free list blocks
	   - whatever various modules and libraries allocate
	*/

	PyGrammar_RemoveAccelerators(&_PyParser_Grammar);

	call_ll_exitfuncs();

#ifdef Py_TRACE_REFS
	_Py_ResetReferences();
#endif /* Py_TRACE_REFS */
}
コード例 #28
0
void ScripterCore::slotRunScript(const QString Script)
{
	// Prevent two scripts to be run concurrently or face crash!
	if (ScCore->primaryMainWindow()->scriptIsRunning())
		return;
	disableMainWindowMenu();

	ScCore->primaryMainWindow()->propertiesPalette->unsetDoc();
	ScCore->primaryMainWindow()->pagePalette->setView(NULL);
	ScCore->primaryMainWindow()->setScriptRunning(true);
	inValue = Script;
	QString cm;
	cm = "# -*- coding: utf8 -*- \n";
	if (PyThreadState_Get() != NULL)
	{
		initscribus(ScCore->primaryMainWindow());
		/* HACK: following loop handles all input line by line.
		It *should* use I.C. because of docstrings etc. I.I. cannot
		handle docstrings right.
		Calling all code in one command:
		ia = code.InteractiveInterpreter() ia.runsource(getval())
		works fine in plain Python. Not here. WTF? */
		cm += (
				"try:\n"
				"    import cStringIO\n"
				"    scribus._bu = cStringIO.StringIO()\n"
				"    sys.stdout = scribus._bu\n"
				"    sys.stderr = scribus._bu\n"
				"    sys.argv = ['scribus']\n" // this is the PySys_SetArgv replacement
				"    scribus.mainInterpreter = True\n" // the scripter console runs everything in the main interpreter
				"    for i in scribus.getval().splitlines():\n"
				"        scribus._ia.push(i)\n"
				"    scribus.retval(scribus._bu.getvalue())\n"
				"    sys.stdout = sys.__stdout__\n"
				"    sys.stderr = sys.__stderr__\n"
				"except SystemExit:\n"
				"    print 'Catched SystemExit - it is not good for Scribus'\n"
				"except KeyboardInterrupt:\n"
				"    print 'Catched KeyboardInterrupt - it is not good for Scribus'\n"
			  );
	}
	// Set up sys.argv
	/* PV - WARNING: THIS IS EVIL! This code summons a crash - see
	bug #3510. I don't know why as the Python C API is a little
	bit magic for me. It looks like it replaces the cm QString or what...
	"In file tools/qgarray.cpp, line 147: Out of memory"
	Anyway - sys.argv is set above
	char* comm[1];
	comm[0] = const_cast<char*>("scribus");
	PySys_SetArgv(1, comm); */
	// then run the code
	PyObject* m = PyImport_AddModule((char*)"__main__");
	if (m == NULL)
		qDebug("Failed to get __main__ - aborting script");
	else
	{
		PyObject* globals = PyModule_GetDict(m);
		PyObject* result = PyRun_String(cm.toUtf8().data(), Py_file_input, globals, globals);
		if (result == NULL)
		{
			PyErr_Print();
			ScMessageBox::warning(ScCore->primaryMainWindow(), tr("Script error"),
					"<qt>" + tr("There was an internal error while trying the "
					   "command you entered. Details were printed to "
					   "stderr. ") + "</qt>");
		}
		else
		// Because 'result' may be NULL, not a PyObject*, we must call PyXDECREF not Py_DECREF
			Py_XDECREF(result);
	}
	ScCore->primaryMainWindow()->setScriptRunning(false);

	enableMainWindowMenu();
}
コード例 #29
0
int uwsgi_python_init() {

#ifndef UWSGI_PYPY
	char *pyversion = strchr(Py_GetVersion(), '\n');
	if (!pyversion) {
        	uwsgi_log_initial("Python version: %s\n", Py_GetVersion());
	}
	else {
        	uwsgi_log_initial("Python version: %.*s %s\n", pyversion-Py_GetVersion(), Py_GetVersion(), Py_GetCompiler()+1);
	}
#else
	uwsgi_log_initial("PyPy version: %s\n", PYPY_VERSION);
#endif

	if (up.home != NULL) {
#ifdef PYTHREE
		wchar_t *wpyhome;
		wpyhome = malloc((sizeof(wchar_t) * strlen(up.home)) + sizeof(wchar_t) );
		if (!wpyhome) {
			uwsgi_error("malloc()");
			exit(1);
		}
		mbstowcs(wpyhome, up.home, strlen(up.home));
		Py_SetPythonHome(wpyhome);
		// do not free this memory !!!
		//free(wpyhome);
#else
		Py_SetPythonHome(up.home);
#endif
		uwsgi_log("Set PythonHome to %s\n", up.home);
	}


#ifdef PYTHREE
	wchar_t pname[6];
	mbstowcs(pname, "uWSGI", 6);
	Py_SetProgramName(pname);
#else
	Py_SetProgramName("uWSGI");
#endif


#ifndef UWSGI_PYPY
	Py_OptimizeFlag = up.optimize;
#endif

	Py_Initialize();

	if (!uwsgi.has_threads) {
		uwsgi_log("*** Python threads support is disabled. You can enable it with --enable-threads ***\n");
	}

	up.wsgi_spitout = PyCFunction_New(uwsgi_spit_method, NULL);
	up.wsgi_writeout = PyCFunction_New(uwsgi_write_method, NULL);

	up.main_thread = PyThreadState_Get();

        // by default set a fake GIL (little impact on performance)
        up.gil_get = gil_fake_get;
        up.gil_release = gil_fake_release;

        up.swap_ts = simple_swap_ts;
        up.reset_ts = simple_reset_ts;
	

	uwsgi_log_initial("Python main interpreter initialized at %p\n", up.main_thread);

	return 1;

}
コード例 #30
0
void ScripterCore::slotRunScriptFile(QString fileName, QStringList arguments, bool inMainInterpreter)
/** run "filename" python script with the additional arguments provided in "arguments" */
{
	// Prevent two scripts to be run concurrently or face crash!
	if (ScCore->primaryMainWindow()->scriptIsRunning())
		return;
	disableMainWindowMenu();

	PyThreadState *state = NULL;
	QFileInfo fi(fileName);
	QByteArray na = fi.fileName().toLocal8Bit();
	// Set up a sub-interpreter if needed:
	PyThreadState* global_state = NULL;
	if (!inMainInterpreter)
	{
		ScCore->primaryMainWindow()->propertiesPalette->unsetDoc();
		ScCore->primaryMainWindow()->pagePalette->setView(NULL);
		ScCore->primaryMainWindow()->setScriptRunning(true);
		qApp->setOverrideCursor(QCursor(Qt::WaitCursor));
		// Create the sub-interpreter
		// FIXME: This calls abort() in a Python debug build. We're doing something wrong.
		//stateo = PyEval_SaveThread();
		global_state = PyThreadState_Get();
		state = Py_NewInterpreter();
		// Init the scripter module in the sub-interpreter
		initscribus(ScCore->primaryMainWindow());
	}

	// Make sure sys.argv[0] is the path to the script
	arguments.prepend(na.data());
	//convert arguments (QListString) to char** for Python bridge
	/* typically arguments == ['path/to/script.py','--argument1','valueforarg1','--flag']*/
	char **comm = new char*[arguments.size()];
	for (int i = 0; i < arguments.size(); i++)
	{
		QByteArray localStr = arguments.at(i).toLocal8Bit();
		comm[i] = new char[localStr.size() + 1]; //+1 to allow adding '\0'. may be useless, don't know how to check.
		comm[i][localStr.size()] = 0;
		strncpy(comm[i], localStr.data(), localStr.size());
	}
	PySys_SetArgv(arguments.size(), comm);

	for (int i = 0; i < arguments.size(); i++)
		delete[] comm[i];
	delete[] comm;
	
	// call python script
	PyObject* m = PyImport_AddModule((char*)"__main__");
	if (m == NULL)
		qDebug("Failed to get __main__ - aborting script");
	else
	{
		// Path separators need to be escaped on Windows
		QString escapedAbsPath  = QDir::toNativeSeparators(fi.absolutePath()).replace("\\", "\\\\");
		QString escapedFileName = QDir::toNativeSeparators(fileName).replace("\\", "\\\\");
		// FIXME: If filename contains chars outside 7bit ascii, might be problems
		PyObject* globals = PyModule_GetDict(m);
		// Build the Python code to run the script
		//QString cm = QString("from __future__ import division\n"); removed due #5252 PV
		QString cm = QString("import sys\n");
		cm        += QString("import cStringIO\n");
		/* Implementation of the help() in pydoc.py reads some OS variables
		 * for output settings. I use ugly hack to stop freezing calling help()
		 * in script. pv. */
		cm        += QString("import os\nos.environ['PAGER'] = '/bin/false'\n"); // HACK
		cm        += QString("sys.path[0] = \"%1\"\n").arg(escapedAbsPath);
		// Replace sys.stdin with a dummy StringIO that always returns
		// "" for read
		cm        += QString("sys.stdin = cStringIO.StringIO()\n");
		// tell the script if it's running in the main intepreter or a subinterpreter
		cm        += QString("import scribus\n");
		if (inMainInterpreter)
			cm+= QString("scribus.mainInterpreter = True\n");
		else
			cm+= QString("scribus.mainInterpreter = False\n");
		cm        += QString("try:\n");
		cm        += QString("    execfile(\"%1\")\n").arg(escapedFileName);
		cm        += QString("except SystemExit:\n");
		cm        += QString("    pass\n");
		// Capture the text of any other exception that's raised by the interpreter
		// into a StringIO buffer for later extraction.
		cm        += QString("except:\n");
		cm        += QString("    import traceback\n");
		cm        += QString("    _errorMsg = traceback.format_exc()\n");
		if (!ScCore->usingGUI())
			cm += QString("    traceback.print_exc()\n");
		// We re-raise the exception so the return value of PyRun_StringFlags reflects
		// the fact that an exception has ocurred.
		cm        += QString("    raise\n");
		// FIXME: if cmd contains chars outside 7bit ascii, might be problems
		QByteArray cmd = cm.toUtf8();
		// Now run the script in the interpreter's global scope. It'll run in a
		// sub-interpreter if we created and switched to one earlier, otherwise
		// it'll run in the main interpreter.
		PyObject* result = PyRun_String(cmd.data(), Py_file_input, globals, globals);
		// NULL is returned if an exception is set. We don't care about any
		// other return value (most likely None anyway) and can ignore it.
		if (result == NULL)
		{
			PyObject* errorMsgPyStr = PyMapping_GetItemString(globals, (char*)"_errorMsg");
			if (errorMsgPyStr == NULL)
			{
				// It's rather unlikely that this will ever be reached - to get here
				// we'd have to fail to retrive the string we just created.
				qDebug("Error retrieving error message content after script exception!");
				qDebug("Exception was:");
				PyErr_Print();
			}
			else if (ScCore->usingGUI())
			{
				QString errorMsg = PyString_AsString(errorMsgPyStr);
				// Display a dialog to the user with the exception
				QClipboard *cp = QApplication::clipboard();
				cp->setText(errorMsg);
				ScCore->closeSplash();
				qApp->changeOverrideCursor(QCursor(Qt::ArrowCursor));
				ScMessageBox::warning(ScCore->primaryMainWindow(),
									tr("Script error"),
									"<qt><p>"
									+ tr("If you are running an official script report it at <a href=\"http://bugs.scribus.net\">bugs.scribus.net</a> please.")
									+ "</p><pre>" + errorMsg.toHtmlEscaped() + "</pre><p>"
									+ tr("This message is in your clipboard too. Use Ctrl+V to paste it into bug tracker.")
									+ "</p></qt>");
			}
			// We've already processed the exception text, so clear the exception
			PyErr_Clear();
		} // end if result == NULL
		// Because 'result' may be NULL, not a PyObject*, we must call PyXDECREF not Py_DECREF
		Py_XDECREF(result);
	} // end if m == NULL
	if (!inMainInterpreter)
	{
		Py_EndInterpreter(state);
		PyThreadState_Swap(global_state);
		//PyEval_RestoreThread(stateo);
		qApp->restoreOverrideCursor();
		ScCore->primaryMainWindow()->setScriptRunning(false);
	}

	enableMainWindowMenu();
}