Beispiel #1
0
int
PyObject_DelItem(PyObject *o, PyObject *key)
{
	PyMappingMethods *m;

	if (o == NULL || key == NULL) {
		null_error();
		return -1;
	}
	m = o->ob_type->tp_as_mapping;
	if (m && m->mp_ass_subscript)
		return m->mp_ass_subscript(o, key, (PyObject*)NULL);

	if (o->ob_type->tp_as_sequence) {
		if (PyInt_Check(key))
			return PySequence_DelItem(o, PyInt_AsLong(key));
		else if (PyLong_Check(key)) {
			long key_value = PyLong_AsLong(key);
			if (key_value == -1 && PyErr_Occurred())
				return -1;
			return PySequence_DelItem(o, key_value);
		}
		type_error("sequence index must be integer");
		return -1;
	}

	type_error("object does not support item deletion");
	return -1;
}
Beispiel #2
0
static void
_psyco_conn_close(connobject *self)
{
    int len, i;
    PyObject *tmpobj = NULL;
    connkeeper *keeper;
    
    Dprintf("_psyco_conn_close(): closing all cursors\n");
    curs_closeall(self);

    /* orphans all the children cursors but do NOT destroy them (note that
       we need to lock the keepers used by the cursors before destroying the
       connection, else we risk to be inside an execute while we set pgconn
       to NULL) */
    assert(self->cursors != NULL);
    len = PyList_Size(self->cursors);
    Dprintf("_psyco_conn_close(): len(self->cursors) = %d\n", len);
    for (i = len-1; i >= 0; i--) {
        tmpobj = PyList_GetItem(self->cursors, i);
        assert(tmpobj);
        Dprintf("_psyco_conn_close(): detaching cursor at %p: refcnt = %d\n",
                tmpobj, tmpobj->ob_refcnt);
        Py_INCREF(tmpobj);
        PySequence_DelItem(self->cursors, i);
        dispose_pgconn((cursobject *)tmpobj);
        ((cursobject *)tmpobj)->conn = NULL; /* orphaned */
        Dprintf("_psyco_conn_close(): cursor at %p detached: refcnt = %d\n",
                tmpobj, tmpobj->ob_refcnt);
    }

    /* close all the open postgresql connections */
    len = PyList_Size(self->avail_conn);
    Dprintf("_psyco_conn_close(): len(self->avail_conn) = %d\n", len);
    for (i = len-1; i >= 0; i--) {
        tmpobj = PyList_GetItem(self->avail_conn, i);
        assert(tmpobj);
        Py_INCREF(tmpobj);
        if ((keeper = (connkeeper *)PyCObject_AsVoidPtr(tmpobj))) {
            Dprintf("_psyco_conn_close(): destroying avail_conn[%i] at %p\n",
                    i, keeper);
            PQfinish(keeper->pgconn);
            pthread_mutex_destroy(&(keeper->lock));
            free(keeper);
        }
        PySequence_DelItem(self->avail_conn, i);
        Py_DECREF(tmpobj);
    }
    
    Py_DECREF(self->cursors);
    Py_DECREF(self->avail_conn);
    self->cursors = NULL;
    self->avail_conn = NULL;

    /* orphan default cursor and destroy it (closing the last connection to the
       database) */
    Dprintf("_psyco_conn_close(): killing stdmanager\n");
    self->stdmanager->conn = NULL;
    Py_DECREF(self->stdmanager);
    self->stdmanager = NULL;
}
// dtor
static void
AtTime_dealloc( PyObject* self ) {
	AtTime * at = (AtTime*)self;
	
	PyObject * tsd = PyThreadState_GetDict();
	PyObject * atd = PyDict_GetItemString(tsd, "_AtTime" );
	if( atd ) {
		PyObject * cur_stack = PyDict_GetItemString( atd, "current_stack" );
		PyObject * time_stack = PyDict_GetItemString( atd, "time_stack" );
		
		Py_ssize_t time_top = PyList_Size(time_stack) - 1;
		PyObject * hashKey = PyLong_FromLong( PyObject_Hash((PyObject*)self) );
		Py_ssize_t pos = PySequence_Index(cur_stack, hashKey);
		Py_DECREF(hashKey);
		
		// Restore the correct time value if we are current
		if( PyList_Size(cur_stack) == pos + 1 ) {
			thread_local(current_time) = PyLong_AsLong( PyList_GetItem( time_stack, time_top ) );
			//PySys_WriteStdout( "Current AtTime object destroyed, restoring thread_local(current_time) to %i\n", thread_local(current_time) );
			PySequence_DelItem(time_stack,time_top);
		} else
			// If we aren't current, then we delete the time at the position one above where we are in the current_stack
			PySequence_DelItem(time_stack,pos+1);
		
		PySequence_DelItem(cur_stack,pos);
		
		// If we are the last AtTime object local to this thread, then remove the _AtTime thread-local dict
		if( PyList_Size(cur_stack) == 0 ) {
			thread_local(use_time_context) = (PyDict_GetItemString( atd, "restore_use_time_context" ) == Py_True) ? TRUE : FALSE;
			//PySys_WriteStdout( "Last AtTime object destroyed, setting thread_local(use_time_context) to FALSE\n" );
			PyDict_DelItemString(tsd, "_AtTime");
		}
	}
	self->ob_type->tp_free(self);
}
Beispiel #4
0
static int
PySurface_UnlockBy (PyObject* surfobj, PyObject* lockobj)
{
    PySurfaceObject* surf = (PySurfaceObject*) surfobj;
    int found = 0;
    int noerror = 1;

    if (surf->locklist)
    {
        PyObject *item, *ref;
        Py_ssize_t len = PyList_Size (surf->locklist);
        while (--len >= 0 && !found)
        {
            item = PyList_GetItem (surf->locklist, len);
            ref = PyWeakref_GetObject (item);
            if (ref == lockobj)
            {
                if (PySequence_DelItem (surf->locklist, len) == -1)
                    return 0;
                else
                    found = 1;
            }
        }

        /* Clear dead references */
        len = PyList_Size (surf->locklist);
        while (--len >= 0)
        {
            item = PyList_GetItem (surf->locklist, len);
            ref = PyWeakref_GetObject (item);
            if (ref == Py_None)
            {
                if (PySequence_DelItem (surf->locklist, len) == -1)
                    noerror = 0;
                else
                    found++;
            }
        }
    }

    if (!found)
        return noerror;

    /* Release all found locks. */
    while (found > 0)
    {
        if (surf->surf != NULL)
            SDL_UnlockSurface (surf->surf);
        if (surf->subsurface)
            PySurface_Unprep (surfobj);
        found--;
    }

    return noerror;
}
Beispiel #5
0
void
moo_python_remove_path (const char *dir)
{
    PyObject *path;
    int i;

    g_return_if_fail (dir != NULL);

    path = PySys_GetObject ((char*) "path");

    if (!path || !PyList_Check (path))
        return;

    for (i = PyList_GET_SIZE (path) - 1; i >= 0; --i)
    {
        PyObject *item = PyList_GET_ITEM (path, i);

        if (PyString_CheckExact (item) &&
            !strcmp (PyString_AsString (item), dir))
        {
            if (PySequence_DelItem (path, i) != 0)
                PyErr_Print ();
            break;
        }
    }
}
Beispiel #6
0
	bool PSequence::DelItem(Py_ssize_t i) {
		if (!this->myObject) { throw new NULLPyObjectException(); }
		if (PySequence_DelItem(this->myObject, i) == -1) {
			return false;
		}
		return true;
	}
Beispiel #7
0
void idle_cb(struct ev_loop *loop, ev_idle *w, int revents)
{
    int listsize;
    

    listsize=PyList_Size(pydeferqueue);
    if (listsize>0)
    {
        PyObject *pyelem=PySequence_GetItem(pydeferqueue,0); 
        PyObject *pyfct=PySequence_GetItem(pyelem,0);
        PyObject *pyfctargs=PySequence_GetItem(pyelem,1);
        //execute the python code
        if (debug) printf("Execute 1 python function in defer mode:%i\n", listsize);
        PyObject *response = PyObject_CallFunctionObjArgs(pyfct, pyfctargs, NULL); 
        if (response==NULL) 
        {
            printf("ERROR!!!! Defer callback function as a problem. \nI remind that it takes always one argumet\n");
            PyErr_Print();
            //exit(1);
        }
        Py_XDECREF(response);
        Py_DECREF(pyfct);
        Py_DECREF(pyfctargs);
        Py_DECREF(pyelem);
        //remove the element
        PySequence_DelItem(pydeferqueue,0); // don't ask me why, but the delitem has to be after the decrefs
    } else
    {
        //stop idle if queue is empty
        if (debug) printf("stop ev_idle\n");
        ev_idle_stop(loop, w);
        Py_DECREF(pydeferqueue);
        pydeferqueue=NULL;
    }
}
Beispiel #8
0
int pyloader_unload_script(const char *name)
{
    int id;
    PyObject *script = py_get_script(name, &id);

    if (!script)
    {
        printtext(NULL, NULL, MSGLEVEL_CLIENTERROR, "%s is not loaded", name); 
        return 0;
    }

    /* PySys_WriteStdout("unload %s, script -> 0x%x\n", name, script); */
    
    pyscript_cleanup(script);

    if (PySequence_DelItem(script_modules, id) < 0)
    {
        PyErr_Print();
        printtext(NULL, NULL, MSGLEVEL_CLIENTERROR, "error unloading script %s", name); 
        return 0;
    }

    /* Probably a good time to call the garbage collecter to clean up reference cycles */
    PyGC_Collect();
    printtext(NULL, NULL, MSGLEVEL_CLIENTERROR, "unloaded script %s", name); 
    
    return 1; 
}
Beispiel #9
0
/**
 *  关闭连接
 *  args[0] 连接对象
 *  args[1] 连接池对象
 **/
static PyObject*
connect_close(PyObject *self, PyObject *args)
{
    PyConnectPoolObject *pool = (PyConnectPoolObject*)PySequence_GetItem(args, 1);
    PyConnectObject *con = (PyConnectObject*)PySequence_GetItem(args, 0);
    int index;
    if(!pool || !con || !PyConnectPool_CheckExact(pool) || !PyConnect_CheckExact(con))
    {
        PyErr_SetString(PyExc_RuntimeError, "参数错误");
        return NULL;
    }
    //从busy连接队列中删除掉
    index = PySequence_Index(pool->cons_busy, (PyObject*)con);
    if(index != -1)
        PySequence_DelItem(pool->cons_busy, index);
    //检查空闲的连接池数量
    //如果空闲的连接过多,则关闭多余的连接
    if(PySequence_Length(pool->cons_free) > pool->free_max)
    {
        connect_dealloc(con);
    }
    else
    {
        PyList_Insert((PyObject*)(pool->cons_free), 0, (PyObject*)con);
    }
    return Py_True;
}
Beispiel #10
0
/*
 * Travel all the mapped drive to check whether there is duplicated
 * shared folder:
 *
 *   Return 1 if current share folder is same or sub-folder of the
 *   mapped folder;
 *
 *   Return -1 if unknown exception occurs;
 *
 *   Remove mapped item from list if the mapped folder is sub-folder
 *   of current share folder.
 *
 * Return 0 if it's new share folder.
 *
 */
static int
check_duplicate_shared_folder(PyObject *retvalue, const char *folder)
{
  if (!PyList_Check(retvalue))
    return -1;

  Py_ssize_t size = PyList_Size(retvalue);
  int len = strlen(folder);
  int len2;
  PyObject *item;
  char * s;

  while (size > 0) {
    size --;
    item = PySequence_GetItem(retvalue, size);
    if (!PySequence_Check(item))
      return -1;
    s = PyString_AsString(PySequence_GetItem(item, 1));
    if (s == NULL)
      return -1;
    len2 = strlen(s);

    if (strncmp(folder, s, len > len2 ? len : len2) == 0) {
      if (len2 > len) {
        if (PySequence_DelItem(retvalue, size) == -1)
          return -1;
        size --;
      }
      else
        return 1;
    }
  }
  return 0;
}
Beispiel #11
0
static int ws_onclose(libwebsock_client_state *state)
{
  //generate python client state object and call python callable
  PyObject *stateObject = NULL;
  PyObject *arglist;

  PyObject **clients_array;

  Py_ssize_t clients_len;
  int clients_idx;

  clients_len = PySequence_Size(connected_clients_list);
  clients_array = PySequence_Fast_ITEMS(connected_clients_list);

  for(clients_idx = 0; clients_idx < clients_len; clients_array++, clients_idx++) {
    if(*clients_array && ((libwebsock_ClientStateObject *)*clients_array)->state == state) {
      stateObject = *clients_array;
      break;
    }
  }

  if(stateObject) {
    PySequence_DelItem(connected_clients_list, PySequence_Index(connected_clients_list, stateObject));
    if(onclose_callback) {
      arglist = Py_BuildValue("(O)", stateObject);
      PyObject_CallObject(onclose_callback, arglist);
      Py_DECREF(arglist);
    }
    Py_DECREF(stateObject);
  }
  return 0;
}
Beispiel #12
0
void clear_PySequence(PyObject *list )
{
  int i;
  int n = PySequence_Length(list);
  for(i=0;i<n;i++){
    PySequence_DelItem(list,0);
  }
}
Beispiel #13
0
PyObject *Timer_end(Timer *self, PyObject *args) {
    if (!(self->flags & TIMER_ACTIVE))
        Py_RETURN_NONE;
        
    if (PySequence_DelItem(ACTIVE_TIMERS, PySequence_Index(ACTIVE_TIMERS, (PyObject *)self)) == -1)
        return NULL;
    self->flags &= ~TIMER_ACTIVE;
    
    POST_EVENT(self, TIMER_END);
    
    Py_RETURN_NONE;
}
Beispiel #14
0
static int
symtable_exit_block(struct symtable *st, void *ast)
{
    Py_ssize_t end;

    Py_CLEAR(st->st_cur);
    end = PyList_GET_SIZE(st->st_stack) - 1;
    if (end >= 0) {
        st->st_cur = (PySTEntryObject *)PyList_GET_ITEM(st->st_stack,
                                                        end);
        if (st->st_cur == NULL)
            return 0;
        Py_INCREF(st->st_cur);
        if (PySequence_DelItem(st->st_stack, end) < 0)
            return 0;
    }
    return 1;
}
Beispiel #15
0
static PyObject *
evregpy_disconnect (PyObject *self, PyObject *function)
{
  PyObject *func;
  int index;
  PyObject *callback_list = (((eventregistry_object *) self)->callbacks);

  if (!PyArg_ParseTuple (function, "O", &func))
    return NULL;

  index = PySequence_Index (callback_list, func);
  if (index < 0)
    Py_RETURN_NONE;

  if (PySequence_DelItem (callback_list, index) < 0)
    return NULL;

  Py_RETURN_NONE;
}
Beispiel #16
0
PyObject *sync(PyObject *self, PyObject *args) {
    
    long int c;
    PyArg_ParseTuple(args, "l", &c);
    
    Timer *timer;
    int i, length = PySequence_Length(ACTIVE_TIMERS);
    int offset = 0;
    
    for (i = 0; i < length; i++) {
        timer = (Timer *)PyList_GET_ITEM(ACTIVE_TIMERS, i - offset);
        if (Timer_sync(timer, c) == -2) {
            if (PySequence_DelItem(ACTIVE_TIMERS, i) == -1) {
                return NULL;
            }
            offset += 1;
        }
    } 
    Py_RETURN_NONE;
}
Beispiel #17
0
static int t_sequence_seq_set(t_sequence *self, Py_ssize_t i, PyObject *value)
{
    int result;

    if (value == NULL)
        result = PySequence_DelItem(self->sequence, i);
    else if (self->itemvalue.flags & V_PURE)
        result = PySequence_SetItem(self->sequence, i, value);
    else
    {
        value = _prepareValue(self, value);
        if (!value)
            return -1;

        result = PySequence_SetItem(self->sequence, i, value);
        Py_DECREF(value);
    }

    if (result >= 0)
        result = _t_itemvalue__setDirty((t_itemvalue *) self, 0);

    return result;
}
Beispiel #18
0
static PyObject *t_sequence_pop(t_sequence *self, PyObject *args)
{
    int index = -1, setDirty = 1;
    PyObject *value;

    if (!PyArg_ParseTuple(args, "|ii", &index, &setDirty))
        return NULL;

    value = PySequence_GetItem(self->sequence, index);
    if (!value)
        return NULL;

    if (!(self->itemvalue.flags & V_PURE))
    {
        PyObject *v = _restoreValue(self, value);
        Py_DECREF(value);
        
        if (!v)
            return NULL;
        value = v;
    }

    if (PySequence_DelItem(self->sequence, index) < 0)
    {
        Py_DECREF(value);
        return NULL;
    }

    if (setDirty && _t_itemvalue__setDirty((t_itemvalue *) self, 0) < 0)
    {
        Py_DECREF(value);
        return NULL;
    }

    return value;
}
Beispiel #19
0
static void __pyx_f_6brown1_f(void) {
  int __pyx_v_key;
  PyListObject *__pyx_v_l;
  PyObject *__pyx_v_d;
  PyObject *__pyx_1 = 0;
  __pyx_v_l = ((PyListObject *)Py_None); Py_INCREF(Py_None);
  __pyx_v_d = Py_None; Py_INCREF(Py_None);

  /* "/Local/Projects/D/Pyrex/Source/Tests/Bugs/brown/brown1.pyx":6 */
  if (PySequence_DelItem(((PyObject *)__pyx_v_l), __pyx_v_key) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 6; goto __pyx_L1;}

  /* "/Local/Projects/D/Pyrex/Source/Tests/Bugs/brown/brown1.pyx":7 */
  __pyx_1 = PyInt_FromLong(__pyx_v_key); if (!__pyx_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 7; goto __pyx_L1;}
  if (PyObject_DelItem(__pyx_v_d, __pyx_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 7; goto __pyx_L1;}
  Py_DECREF(__pyx_1); __pyx_1 = 0;

  goto __pyx_L0;
  __pyx_L1:;
  Py_XDECREF(__pyx_1);
  __Pyx_WriteUnraisable("brown1.f");
  __pyx_L0:;
  Py_DECREF(__pyx_v_l);
  Py_DECREF(__pyx_v_d);
}
Beispiel #20
0
int py_plugin_open(struct plugin *plugin, char *dir)
{
	PyObject *handle, *info;
	PyObject *PyStr;
	PyObject *PyErrType, *PyErr, *PyTraceback;

	if (!(PyStr = PyString_FromString(dir))) {
		PyErr_Print();
		return -1;
	}

	if (PyList_Insert(PyPath, 0, PyStr)) {
		Py_DECREF(PyStr);
		return -1;
	}

	if (!(handle = PyImport_ImportModule(plugin->name))) {
		/* ignore "module not found" errors in top level module */
		PyErr_Fetch(&PyErrType, &PyErr, &PyTraceback);
		PyErr_NormalizeException(&PyErrType, &PyErr, &PyTraceback);
		if (PyErr_GivenExceptionMatches(PyErr, PyExc_ImportError) &&
		  !PyTraceback) {
			Py_XDECREF(PyErrType);
			Py_XDECREF(PyErr);
		}
		else {
			PyErr_Restore(PyErrType, PyErr, PyTraceback);
			PyErr_Print();
		}

		if (PySequence_DelItem(PyPath, 0)) {
			PyErr_Print();
		}
		Py_DECREF(PyStr);
		return -1;
	}

	if (PySequence_DelItem(PyPath, 0)) {
		PyErr_Print();
	}
	Py_DECREF(PyStr);

	if (!(plugin->p = malloc(sizeof(struct py_plugin)))) {
		wminput_err("Error allocating py_plugin");
		return -1;
	}

	plugin->type = PLUGIN_PYTHON;
	plugin->info = NULL;
	plugin->data = NULL;
	((struct py_plugin *) plugin->p)->init = NULL;
	((struct py_plugin *) plugin->p)->exec = NULL;

	if (!(plugin->info = malloc(sizeof *plugin->info))) {
		wminput_err("Error allocating plugin info");
		goto ERR_HND;
	}
	if (!(plugin->data = malloc(sizeof *plugin->data))) {
		wminput_err("Error allocating plugin data");
		goto ERR_HND;
	}
	if (!(((struct py_plugin *)plugin->p)->init =
	  PyObject_GetAttrString(handle, "wmplugin_init"))) {
		PyErr_Print();
		goto ERR_HND;
	}
	if (!PyCallable_Check(((struct py_plugin *)plugin->p)->init)) {
		wminput_err("Unable to load plugin init function: not callable");
		goto ERR_HND;
	}
	if (!(((struct py_plugin *)plugin->p)->exec =
	  PyObject_GetAttrString(handle, "wmplugin_exec"))) {
		PyErr_Print();
		goto ERR_HND;
	}
	if (!PyCallable_Check(((struct py_plugin *)plugin->p)->exec)) {
		wminput_err("Unable to load plugin exec function: not callable");
		goto ERR_HND;
	}
	if (!(info = PyObject_GetAttrString(handle, "wmplugin_info"))) {
		PyErr_Print();
		goto ERR_HND;
	}
	if (!PyCallable_Check(info)) {
		wminput_err("Unable to load plugin info function: not callable");
		Py_DECREF((PyObject *)info);
		goto ERR_HND;
	}
	if (py_plugin_info(plugin, info)) {
		wminput_err("Error on python_info");
		Py_DECREF((PyObject *)info);
		goto ERR_HND;
	}
	Py_DECREF((PyObject *)info);

	((struct py_plugin *) plugin->p)->handle = handle;

	return 0;

ERR_HND:
	if (plugin->info) {
		free(plugin->info);
	}
	if (plugin->data) {
		free(plugin->data);
	}
	if (plugin->p) {
		if (((struct py_plugin *)plugin->p)->init) {
			Py_DECREF(((struct py_plugin *)plugin->p)->init);
		}
		if (((struct py_plugin *)plugin->p)->exec) {
			Py_DECREF(((struct py_plugin *)plugin->p)->exec);
		}
		free(plugin->p);
	}
	Py_DECREF(handle);
	return -1;
}
Beispiel #21
0
PyObject* wrap_search_neighbors(PyObject *self, PyObject *args)
{
  PyObject *atomlist;
  real cutoff;
  bool build_bonds;
  if(!PyArg_ParseTuple(args,"Odi",&atomlist,&cutoff,&build_bonds))
    return NULL;
  
  int natoms = PySequence_Length(atomlist);
  rvec x[natoms];
  int *nlist[natoms];
  int nat[natoms];


  int i, k;
  for(i=0;i<natoms;i++){
    nat[i] = 0;
    nlist[i] = malloc(sizeof(int));
    PyObject *py_atom = PySequence_GetItem(atomlist, i);
    PyObject *Ox = PyObject_GetAttrString(py_atom,"x");
    Pyvec2rvec(Ox, x[i] );
  }

  search_neighbors(x, natoms, cutoff, nlist, nat);

  if( build_bonds ) {
    reset_bond_lists( atomlist );
  }


  // reset neighborlists
  for(i=0;i<natoms;i++){
    PyObject *atom = PySequence_Fast_GET_ITEM(atomlist, i);
    PyObject *neighbor_list = PyObject_GetAttrString(atom,"neighbors"); 
    int list_size = PySequence_Length( neighbor_list );
    for(k=0;k<list_size;k++){
      PySequence_DelItem(neighbor_list,0);
    }
  }

  if( build_bonds ) {
    build_bonds_by_distance( atomlist, nlist, nat );
    build_b13_from_bonds( atomlist );
    build_b14_from_bonds( atomlist );
  }

  con_table *t = build_table( atomlist );


  for(i=0;i<natoms;i++){
    //    PyObject *atom = PySequence_GetItem(atomlist, i);
    PyObject *atom = PySequence_Fast_GET_ITEM(atomlist, i);
    int atom_id = PyInt_AsLong(PyObject_GetAttrString(atom,"id")) - 1;
    PyObject *neighbor_list = PyObject_GetAttrString(atom,"neighbors");
    for(k=0;k<nat[i];k++){
      int id = nlist[i][k];
      if( ! id_in_con_table( t, atom_id, id ) ){
	PyObject *neighbor_atom = PySequence_Fast_GET_ITEM(atomlist, id);
	PyObject *n_neighborlist = PyObject_GetAttrString(neighbor_atom,"neighbors");
	PyList_Append( neighbor_list, neighbor_atom);
	PyList_Append( n_neighborlist, atom);
      }
    }
  }
  delete_con_table(t);
  for(i=0;i<natoms;i++){
    free(nlist[i]);
  }

  return Py_BuildValue("i",1); //atomlist;
}
Beispiel #22
0
bool get_plots(const std::string& python_file, std::vector<Plot>& plots) {

    plots.clear();

    std::FILE* f = std::fopen(python_file.c_str(), "r");
    if (!f) {
        std::cerr << "Failed to open '" << python_file << "'" <<std::endl;
        return false;
    }

    const std::string PLOTS_KEY_NAME = "plots";

    // Get a reference to the main module
    // and global dictionary
    PyObject* main_module = PyImport_AddModule("__main__");
    PyObject* global_dict = PyModule_GetDict(main_module);

    // If PyROOT is used inside the script, it performs some cleanups when the python env. is destroyed. This cleanup makes ROOT unusable afterwards.
    // The cleanup function is registered with the `atexit` module.
    // The solution is to not execute the cleanup function. For that, before destroying the python env, we check the list of exit functions,
    // and delete the one from PyROOT if found

    // Ensure the module is loaded
    PyObject* atexit_module = PyImport_ImportModule("atexit");

    // Execute the script
    PyObject* script_result = PyRun_File(f, python_file.c_str(), Py_file_input, global_dict, global_dict);

    if (! script_result) {
        PyErr_Print();
        return false;
    } else {
        PyObject* py_plots = PyDict_GetItemString(global_dict, "plots");
        if (!py_plots) {
            std::cerr << "No 'plots' variable declared in python script" << std::endl;
            return false;
        }

        if (! PyList_Check(py_plots)) {
            std::cerr << "The 'plots' variable is not a list" << std::endl;
            return false;
        }

        size_t l = PyList_Size(py_plots);
        if (! l)
            return true;

        for (size_t i = 0; i < l; i++) {
            PyObject* item = PyList_GetItem(py_plots, i);

            Plot plot;
            if (plot_from_PyObject(item, plot)) {
                plots.push_back(plot);
            }
        }
    }

    PyObject* atexit_exithandlers = PyObject_GetAttrString(atexit_module, "_exithandlers");
    for (size_t i = 0; i < PySequence_Size(atexit_exithandlers); i++) {
        PyObject* tuple = PySequence_GetItem(atexit_exithandlers, i);
        PyObject* f = PySequence_GetItem(tuple, 0);
        PyObject* module = PyFunction_GetModule(f);

        if (module && strcmp(PyString_AsString(module), "ROOT") == 0) {
            PySequence_DelItem(atexit_exithandlers, i);
            break;
        }
    }

    return true;
}
Beispiel #23
0
/*	Set item to LDAPEntry with a case-insensitive key. */
int
LDAPEntry_SetItem(LDAPEntry *self, PyObject *key, PyObject *value) {
	int found = 0;
	int rc = 0;
	int status = 1;
	char *newkey = lowercase(PyObject2char(key));
	LDAPValueList *list;

	/* Search for a match. */
	key = searchLowerCaseKeyMatch(self, key, &found);
	if (found == 1) {
		status = 2;
	}
	if (value != NULL) {
		/* If theres an item with a `dn` key, and with a string value set to the dn attribute. */
		if (strcmp(newkey, "dn") == 0) {
			if (PyUnicode_Check(value)) {
				char *dnstr = PyObject2char(value);
				LDAPEntry_SetStringDN(self, dnstr);
				free(dnstr);
			} else {
				PyErr_SetString(PyExc_TypeError, "Distinguished name must be string type.");
				Py_DECREF(key);
				return -1;
			}
		} else {
			/* Set the new value to the item. */
			if (LDAPValueList_Check(value) == 0) {
				/* Convert value to LDAPValueList object. */
				list = LDAPValueList_New();
				if (PyList_Check(value) || PyTuple_Check(value)) {
					LDAPValueList_Extend(list, value);
				} else {
					LDAPValueList_Append(list, value);
				}
				rc = PyDict_SetItem((PyObject *)self, key, (PyObject *)list);
				list->status = status;
				Py_DECREF(list);
			} else {
				rc = PyDict_SetItem((PyObject *)self, key, value);
				((LDAPValueList *)value)->status = status;
			}
			/* Avoid inconsistency. (same key in the added and the deleted list) */
			if (PySequence_Contains((PyObject *)self->deleted, key)) {
				if (UniqueList_Remove(self->deleted, key) != 0) return -1;
			}
			if (rc != 0) return rc;
			/* New key should be added to the attribute list. */
			if (found == 0) {
				if (UniqueList_Append(self->attributes, key) != 0) {
					Py_DECREF(key);
					return -1;
				}
			}
		}
	} else {
		/* This means, it has to remove the item. */
		if (PyDict_DelItem((PyObject *)self, key) != 0) return -1;
		if (UniqueList_Append(self->deleted, key) != 0) return -1;
		/* Remove from the attributes list. */
		if (PySequence_DelItem((PyObject *)self->attributes, PySequence_Index((PyObject *)self->attributes, key)) != 0) {
			Py_DECREF(key);
			return -1;
		}
	}
	Py_DECREF(key);
	return 0;
}
 void Sequence::delItem(int index)
 {
     PySequence_DelItem(mPtr, index);
     PW_PyExcept_Check("Sequence::delItem");
 }
 void List::delItem(int index)
 {
     PySequence_DelItem(mPtr, index);
     PW_PyExcept_Check("List::delItem");;
 }
Beispiel #26
0
static PyObject *
snakeoil_iflatten_instance_iternext(snakeoil_iflatten_instance *self) {
	PyObject *tail, *result, *iter;
	int n, res;

	if (self->in_iternext) {
		/* We do not allow this because it means our list could be
		 * manipulated while we are running. Exception raised matches
		 * what a generator raises if you try the same thing.
		 */
		PyErr_SetString(
			PyExc_ValueError,
			"Recursive calls to iflatten_instance.next are illegal");
		return NULL;
	}
	self->in_iternext = 1;

	/* Look at the final iterator on our stack: */
	while (n = PyList_GET_SIZE(self->iterables)) {
		tail = PyList_GET_ITEM(self->iterables, n - 1);

		/* See if it has any results left: */
		/* (This reference is borrowed from the list, but since we
		   disallow recursive calls in here it should be safe to not
		   increment it). */

		result = PyIter_Next(tail);
		if (result) {
			/* See if we need to iterate over this new result: */

			res = PyObject_IsInstance(result, self->skip_flattening);
			if (res == -1) {
				Py_DECREF(result);
				result = NULL;
			} else if (!res) {

				/* If it is an iterator add it to our chain, else return it. */
				iter = PyObject_GetIter(result);
				if (!iter) {
					/* If we get here PyObject_GetIter raised an exception.
					 * If it was TypeError we have a non-iterator we can
					 * just return, else we propagate the error.
					 */
					if (PyErr_ExceptionMatches(PyExc_TypeError)) {
						PyErr_Clear();
					} else {
						Py_DECREF(result);
						result = NULL;
					}
				}
				if (PyString_Check(result)) {
					/* Block infinite recursion of single char strings */
					Py_ssize_t len = PyObject_Length(result);
					if (-1 == len) {
						Py_DECREF(result);
						Py_DECREF(iter);
						return NULL;
					}
					if (len <= 1) {
						Py_CLEAR(iter);
					}
				}

				if (iter) {
					/* Iterable, append to our stack and continue.
					 * */
					Py_DECREF(result);
					result = NULL;
					res = PyList_Append(self->iterables, iter);
					Py_DECREF(iter);
					if (res != -1) {
						continue;
					}
					/* Fall through and propagate the error. */
				}
			}
		} else {
			/* PyIter_Next did not return an item. If this was not
			 * because of an error we should pop the exhausted
			 * iterable off and continue. */
			if (!PyErr_Occurred() &&
				PySequence_DelItem(self->iterables, n - 1) != -1) {
				continue;
			}
		}
		self->in_iternext = 0;
		return result;
	}

	/* We ran out of iterables entirely, so we are done */
	self->in_iternext = 0;
	return NULL;
}