Exemple #1
0
/// Return the log buffer up to limit as a python list. Called by management agent.
PyObject *qd_log_recent_py(long limit) {
    if (PyErr_Occurred()) return NULL;
    PyObject *list = PyList_New(0);
    PyObject *py_entry = NULL;
    if (!list) goto error;
    qd_log_entry_t *entry = DEQ_TAIL(entries);
    while (entry && limit) {
        const int ENTRY_SIZE=6;
        py_entry = PyList_New(ENTRY_SIZE);
        if (!py_entry) goto error;
        int i = 0;
        // NOTE: PyList_SetItem steals a reference so no leak here.
        PyList_SetItem(py_entry, i++, PyString_FromString(entry->module));
        const char* level = level_name(entry->level);
        PyList_SetItem(py_entry, i++, level ? PyString_FromString(level) : inc_none());
        PyList_SetItem(py_entry, i++, PyString_FromString(entry->text));
        PyList_SetItem(py_entry, i++, entry->file ? PyString_FromString(entry->file) : inc_none());
        PyList_SetItem(py_entry, i++, entry->file ? PyLong_FromLong(entry->line) : inc_none());
        PyList_SetItem(py_entry, i++, PyLong_FromLongLong((PY_LONG_LONG)entry->time));
        assert(i == ENTRY_SIZE);
        if (PyErr_Occurred()) goto error;
        PyList_Insert(list, 0, py_entry);
        Py_DECREF(py_entry);
        if (limit > 0) --limit;
        entry = DEQ_PREV(entry);
    }
    return list;
 error:
    Py_XDECREF(list);
    Py_XDECREF(py_entry);
    return NULL;
}
	static void PyListInsertString(
		PyObject *list, int index, std::string string)
	{
		PyObject* s = PyString_FromString(string.c_str());
		PyList_Insert(list, 0, s);
		Py_XDECREF(s);
	}
Exemple #3
0
static void setupPyPath(void)
{
    PyObject *mod, *path = NULL;

    mod = PyImport_ImportModule("sys");
    if(mod)
        path = PyObject_GetAttrString(mod, "path");
    Py_XDECREF(mod);

    if(path) {
        PyObject *cur;
        char cwd[PATH_MAX];

        insertDefaultPath(path);

        /* prepend current directory */
        if(getcwd(cwd, sizeof(cwd)-1)) {
            cwd[sizeof(cwd)-1] = '\0';
            cur = PyString_FromString(cwd);
            if(cur)
                PyList_Insert(path, 0, cur);
            Py_XDECREF(cur);
        }
    }
    Py_XDECREF(path);
}
Exemple #4
0
static int proxenet_python_append_path()
{
	PyObject *pPath, *pAddPath;
	int retcode = 0;

	pPath = PySys_GetObject("path");
	if (!pPath) {
		xlog_python(LOG_ERROR, "%s\n", "Failed to find `sys.path'");
		return -1;
	}

	if (!PyList_Check(pPath)) {
		return -1;
	}

	pAddPath = PYTHON_FROMSTRING(cfg->plugins_path);
	if (!pAddPath) {
		return -1;
	}

	if (PyList_Insert(pPath, 0, pAddPath) < 0) {
		retcode = -1;
	}
	Py_DECREF(pAddPath);

	return retcode;
}
Exemple #5
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;
}
Exemple #6
0
/**
 * Add an additional search directory for the protocol decoders.
 *
 * The specified directory is prepended (not appended!) to Python's sys.path,
 * in order to search for sigrok protocol decoders in the specified
 * directories first, and in the generic Python module directories (and in
 * the current working directory) last. This avoids conflicts if there are
 * Python modules which have the same name as a sigrok protocol decoder in
 * sys.path or in the current working directory.
 *
 * @param path Path to the directory containing protocol decoders which shall
 *             be added to the Python sys.path, or NULL.
 *
 * @return SRD_OK upon success, a (negative) error code otherwise.
 *
 * @private
 *
 * @since 0.1.0
 */
SRD_PRIV int srd_decoder_searchpath_add(const char *path)
{
	PyObject *py_cur_path, *py_item;

	srd_dbg("Adding '%s' to module path.", path);

	py_cur_path = PySys_GetObject("path");
	if (!py_cur_path)
		return SRD_ERR_PYTHON;

	py_item = PyUnicode_FromString(path);
	if (!py_item) {
		srd_exception_catch(NULL, "Failed to create Unicode object");
		return SRD_ERR_PYTHON;
	}
	if (PyList_Insert(py_cur_path, 0, py_item) < 0) {
		srd_exception_catch(NULL, "Failed to insert path element");
		Py_DECREF(py_item);
		return SRD_ERR_PYTHON;
	}
	Py_DECREF(py_item);

	searchpaths = g_slist_prepend(searchpaths, g_strdup(path));

	return SRD_OK;
}
Exemple #7
0
/**
 *  从连接池中获得一个连接
 *	args的第一个参数是一个连接池对象
 **/
static PyObject*
getconnection(PyObject *self, PyObject *args)
{
    PyConnectPoolObject *pool = PySequence_GetItem(args, 0);
    PyListObject *conns;
    PyConnectObject *con;
    if(!PyConnectPool_CheckExact(pool))
    {
        PyErr_SetString(PyExc_RuntimeError, "参数类型不是connectPool");
        return NULL;
    }
    conns = pool->cons_free;
    //空闲缓冲池里面可以获得到空闲的连接
    if(PySequence_Length(conns))
    {
        con = (PyConnectObject*)PySequence_GetItem(conns, 0);
        //删除第一个元素
        PyList_SetSlice(conns, 0, 1, NULL);
    }
    else
    {
        con = (PyConnectObject*)PyConnect_New(pool->host, pool->user, pool->passwd, pool->db, pool->port);
    }
    if(con == NULL)
    {
        return PyErr_NoMemory();
    }
    conns = pool->cons_busy;
    PyList_Insert((PyObject*)conns, 0, (PyObject*)con);
    return (PyObject*)con;
}
Exemple #8
0
/**
 *  @free_max 最多的空闲连接数
 *  @begin_conn 开始时打开的连接数
 **/
static PyConnectPoolObject*
init(int free_max, int begin_conn, char *host, char *user, char *passwd,
     char *db, int port)
{
    PyConnectPoolObject *pool;
    PyConnectObject *con;
    int i = 0;
    //参数检查
    begin_conn = (begin_conn < 1) ? 1 : begin_conn;
    begin_conn = (begin_conn > BEGIN_CONN_MAX) ? BEGIN_CONN_MAX : begin_conn;
    //printf("1\n");
    //
    pool = (PyConnectPoolObject*)PyConnectPool_New(free_max, host, user, passwd, db, port);
    if(!pool)
    {
        return NULL;
    }
    //printf("2\n");
    for(i = 0; i < begin_conn; i ++)
    {
        con = (PyConnectObject*)PyConnect_New(pool->host, pool->user, pool->passwd, pool->db, pool->port);
        PyList_Insert(pool->cons_free, 0, (PyObject*)con);
    }
    //printf("3\n");
    return pool;
}
Exemple #9
0
void
QPython::addImportPath(QString path)
{
    ENSURE_GIL_STATE;

    // Strip leading "file://" (for use with Qt.resolvedUrl())
    if (path.startsWith("file://")) {
#ifdef WIN32
        // On Windows, path would be "file:///C:\...", so strip 8 chars to get
        // a Windows-compatible absolute filename to be used as import path
        path = path.mid(8);
#else
        path = path.mid(7);
#endif
    }

    if (SINCE_API_VERSION(1, 3) && path.startsWith("qrc:")) {
        const char *module = "pyotherside.qrc_importer";
        QString filename = "/io/thp/pyotherside/qrc_importer.py";
        QString errorMessage = priv->importFromQRC(module, filename);
        if (!errorMessage.isNull()) {
            emitError(errorMessage);
        }
    }

    QByteArray utf8bytes = path.toUtf8();

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

    PyObjectRef cwd(PyUnicode_FromString(utf8bytes.constData()), true);
    PyList_Insert(sys_path, 0, cwd.borrow());
}
Exemple #10
0
void Plugins::loadFromPath(const ppl6::CString &Path)
{
#ifdef HAVE_PYTHON
	ppl6::CDir Dir;
	if (!Dir.Open(Path)) return;

	PyObject *sysPath = PySys_GetObject("path");
	PyObject *path = PyString_FromString(Path);
	int result = PyList_Insert(sysPath, 0, path);
	Py_DECREF(path);


	Dir.Reset();
	const ppl6::CDirEntry *entry;
	while ((entry=Dir.GetNextPattern("*.py"))) {
		ppl6::CArray matches;
		if (entry->Filename.PregMatch("/^(.*?)\\.py$/i",matches)) {
			ppl6::CString ModuleName=matches.GetString(1);
			printf ("Loading Plugin: %s\n",(const char*)ModuleName);
			python_modules.push_back(ModuleName);
			PyRun_SimpleString("import "+ModuleName+"\n");
		}
	}
#endif
}
Exemple #11
0
void
TraCIServer::runEmbedded(std::string pyFile) {
    PyObject* pName, *pModule;
    Py_Initialize();
    Py_InitModule("traciemb", EmbMethods);
    if (pyFile.length() > 3 && !pyFile.compare(pyFile.length() - 3, 3, ".py")) {
        PyObject* sys_path, *path;
        char pathstr[] = "path";
        sys_path = PySys_GetObject(pathstr);
        if (sys_path == NULL || !PyList_Check(sys_path)) {
            throw ProcessError("Could not access python sys.path!");
        }
        path = PyString_FromString(FileHelpers::getFilePath(pyFile).c_str());
        PyList_Insert(sys_path, 0, path);
        Py_DECREF(path);
        FILE* pFile = fopen(pyFile.c_str(), "r");
        if (pFile == NULL) {
            throw ProcessError("Failed to load \"" + pyFile + "\"!");
        }
        PyRun_SimpleFile(pFile, pyFile.c_str());
        fclose(pFile);
    } else {
        pName = PyString_FromString(pyFile.c_str());
        /* Error checking of pName left out */
        pModule = PyImport_Import(pName);
        Py_DECREF(pName);
        if (pModule == NULL) {
            PyErr_Print();
            throw ProcessError("Failed to load \"" + pyFile + "\"!");
        }
    }
    Py_Finalize();
}
Exemple #12
0
//-----------------------------------------------------------------------------
// SetPathToSearch()
//   Set the path to search. This includes the file (for those situations where
// a zip file is attached to the executable itself), the directory where the
// executable is found (to search for extensions), the exclusive zip file
// name and the shared zip file name.
//-----------------------------------------------------------------------------
static int SetPathToSearch(void)
{
    PyObject *pathList;

    pathList = PySys_GetObject("path");
    if (!pathList)
        return FatalError("cannot acquire sys.path");
    if (PyList_Insert(pathList, 0, g_FileName) < 0)
        return FatalError("cannot insert file name into sys.path");
    if (PyList_Insert(pathList, 1, g_DirName) < 0)
        return FatalError("cannot insert directory name into sys.path");
    if (PyList_Insert(pathList, 2, g_ExclusiveZipFileName) < 0)
        return FatalError("cannot insert exclusive zip name into sys.path");
    if (PyList_Insert(pathList, 3, g_SharedZipFileName) < 0)
        return FatalError("cannot insert shared zip name into sys.path");
    return 0;
}
Exemple #13
0
static gboolean
eom_python_module_load (GTypeModule *gmodule)
{
	EomPythonModulePrivate *priv = EOM_PYTHON_MODULE_GET_PRIVATE (gmodule);
	PyObject *main_module, *main_locals, *locals, *key, *value;
	PyObject *module, *fromlist;
	Py_ssize_t pos = 0;

	g_return_val_if_fail (Py_IsInitialized (), FALSE);

	main_module = PyImport_AddModule ("__main__");

	if (main_module == NULL) {
		g_warning ("Could not get __main__.");
		return FALSE;
	}

	/* If we have a special path, we register it */
	if (priv->path != NULL) {
		PyObject *sys_path = PySys_GetObject ("path");
		PyObject *path = PyString_FromString (priv->path);

		if (PySequence_Contains(sys_path, path) == 0)
			PyList_Insert (sys_path, 0, path);

		Py_DECREF(path);
	}

	main_locals = PyModule_GetDict (main_module);

	/* We need a fromlist to be able to import modules with
         * a '.' in the name. */
	fromlist = PyTuple_New(0);

	module = PyImport_ImportModuleEx (priv->module, main_locals, main_locals, fromlist);

	Py_DECREF(fromlist);

	if (!module) {
		PyErr_Print ();
		return FALSE;
	}

	locals = PyModule_GetDict (module);

	while (PyDict_Next (locals, &pos, &key, &value)) {
		if (!PyType_Check(value))
			continue;

		if (PyObject_IsSubclass (value, (PyObject*) PyEomPlugin_Type)) {
			priv->type = eom_python_plugin_get_type (gmodule, value);
			return TRUE;
		}
	}

	return FALSE;
}
Exemple #14
0
static PyObject *pair_repr(PyObject *self) {
  PyObject *tmp = NULL;
  PyObject *col = PyList_New(0);
  PyObject *found = PyDict_New();
  size_t index = 0;

  PyObject *rest = self;
  PyObject *rest_id;

  PyList_Append(col, _str_cons_paren);

  while (rest->ob_type == &SibPairType) {
    rest_id = PyLong_FromVoidPtr(rest);

    if (PyDict_Contains(found, rest_id)) {
      /* recursive pair detected */
      PyList_Append(col, _str_recursive_true);

      if (rest != self) {
	tmp = PyDict_GetItem(found, rest_id);
	PyList_Insert(col, PyLong_AsSize_t(tmp) - 1, _str_cons_paren);
	PyList_Append(col, _str_close_paren);
      }
      Py_DECREF(rest_id);
      rest = NULL;
      break;

    } else {
      index += 2;

      tmp = PyLong_FromSize_t(index);
      PyDict_SetItem(found, rest_id, tmp);
      Py_DECREF(tmp);

      tmp = PyObject_Repr(SibPair_CAR(rest));
      PyList_Append(col, tmp);
      PyList_Append(col, _str_comma_space);
      Py_DECREF(tmp);

      rest = SibPair_CDR(rest);
      Py_DECREF(rest_id);
    }
  }

  if (rest) {
    PyList_Append(col, PyObject_Repr(rest));
  }

  PyList_Append(col, _str_close_paren);

  tmp = PyUnicode_Join(_str_empty, col);
  Py_DECREF(col);
  Py_DECREF(found);

  return tmp;
}
Exemple #15
0
static PyObject * table_subscript(tableobject *self, register PyObject *key)
{
    char *k;
    const apr_array_header_t *ah;
    apr_table_entry_t *elts;
    register int i;
    PyObject *list;

    if (key && !PyString_Check(key)) {
        PyErr_SetString(PyExc_TypeError,
                        "table keys must be strings");
        return NULL;
    }
    k = PyString_AsString(key);

    /* it's possible that we have duplicate keys, so
       we can't simply use apr_table_get since that just
       returns the first match.
    */

    list = PyList_New(0);
    if (!list) 
        return NULL;

    ah = apr_table_elts (self->table);
    elts = (apr_table_entry_t *) ah->elts;

    i = ah->nelts;

    while (i--)
        if (elts[i].key) {
            if (apr_strnatcasecmp(elts[i].key, k) == 0) {
                PyObject *v = PyString_FromString(elts[i].val);
                PyList_Insert(list, 0, v);
                Py_DECREF(v);
            }
        }

    /* if no mach */
    if (PyList_Size(list) == 0) {
        PyErr_SetObject(PyExc_KeyError, key);
        return NULL;
    }

    /* if we got one match */
    if (PyList_Size(list) == 1) {
        PyObject *v = PyList_GetItem(list, 0);
        Py_INCREF(v);
        Py_DECREF(list);
        return v;
    }

    /* else we return a list */
    return list;
}
Exemple #16
0
void AddPath(const char * path)
{
	PyObject * pName = PyUnicode_FromString(path), *syspath;
	// reference to Python search path
	syspath = PySys_GetObject("path");
	// add path to syspath
	if (PyList_Insert(syspath, 0, pName))
		printf("Error inserting extra path into sys.path list\n");
	// reset sys.path object
	if (PySys_SetObject("path", syspath))
		printf("Error setting sys.path object\n");
}
Exemple #17
0
void PythonModule::add_to_pythonpath(std::string path) {
  if(!initialised) {
      return;
  }
  block_threads();
  PyObject *path_py = PyString_FromString(path.c_str());
  if(PyList_Insert(sys_path, 0, path_py) < 0) {
      PyErr_Print();
  }
  Py_XDECREF(path_py);
  unblock_threads();
}
Exemple #18
0
void list_base::insert(ssize_t index, object_cref item)
{
    if (PyList_CheckExact(this->ptr()))
    {
        if (PyList_Insert(this->ptr(), index, item.ptr()) == -1)
            throw_error_already_set();
    }
    else
    {
        this->attr("insert")(index, item);
    }
}
Exemple #19
0
PyTempleImporter::PyTempleImporter() {
	if (PyType_Ready(&PyTempleImporterType) < 0)
		throw TempleException("Python type has not yet been registered");

	CreateSearchOrder();

	mFinder = PyObject_New(PyObject, &PyTempleImporterType);

	// Insert into python meta_path system
	auto path_hooks = PySys_GetObject("meta_path");
	PyList_Insert(path_hooks, 0, mFinder);
}
Exemple #20
0
    /**
     * \brief          User defined constructor for PyAlgo.
     * \param[in]    file_path         The path of the algorithm python script/module.
     * \param[in]    class_name         Name of the algorithm class.
     */
    PyAlgo( const std::string file_path, const std::string &class_name )
        : base_t()
        , mFilePath( file_path )
        , mClassName( class_name )
	    , m_module( nullptr )
	    , m_class( nullptr )
	    , m_instance( nullptr )
	{
        if ( !IsFile(mFilePath.c_str()) )
            throw e_file_not_found;

        std::string modulePath = dir_from_filepath( file_path );
        std::string moduleName = basename_from_path( file_path );

		// Add the directory (with module) to the python sys.path

        PyObject *sysPath = PySys_GetObject("path");                        //TODO Py_DECREF sysPath???
        PyObject *path    = PyUnicode_FromString( modulePath.c_str() );     //TODO Py_DECREF path???
		if ( PyList_Insert(sysPath, 0, path))
            throw e_error_add_module_dir_syspath;

		// Build the name object and load the module object

        PyObject *pName   = PyUnicode_FromString( moduleName.c_str() );
		m_module = PyImport_Import(pName);
        Py_DECREF(pName);
		if (PyErr_Occurred()){
			PyErr_Print();
			throw e_error_loading_module;
		}

		std::cout << "- Loaded python Module object " + moduleName + " at " << m_module << std::endl;

	    // Build the name of a callable class

		m_class = PyObject_GetAttrString( m_module, mClassName.c_str() );


		// Create an instance of the class

		if (m_class && PyCallable_Check(m_class))
		{
			m_instance = PyObject_CallObject(m_class, NULL);

            std::cout << "-- Loaded a python Class object " + mClassName + " at " << m_class << std::endl;
		}
		else {
			if (PyErr_Occurred())
				PyErr_Print();
			throw e_class_not_found;
		}
    }
PyObject* cyAccountManagement::GetPlayerList()
{
    const ARRAY(NetCommPlayer)& playerList = NetCommGetPlayerList();
    int numPlayers = NetCommGetPlayerCount();
    PyObject* pList = PyList_New(0);

    PyObject* visitor = nil;

    for (int i = 0; i < numPlayers; ++i)
    {
        PyObject* playerTuple   = PyTuple_New(3);
        PyObject* playerName    = PyUnicode_FromStringEx(playerList[i].playerName);
        PyObject* playerId      = PyInt_FromLong(playerList[i].playerInt);
        PyObject* avatarShape   = PyString_FromPlString(playerList[i].avatarDatasetName);

        PyTuple_SetItem(playerTuple, 0, playerName);
        PyTuple_SetItem(playerTuple, 1, playerId);
        PyTuple_SetItem(playerTuple, 2, avatarShape);

        if (visitor || playerList[i].explorer)
            PyList_Append(pList, playerTuple);
        else
            visitor = playerTuple;
    }

    if (visitor)
    {
        PyList_Insert(pList, 0, visitor);
    }
    else
    {
        Py_INCREF(Py_None);
        PyList_Insert(pList, 0, Py_None);
    }

    return pList;
}
Exemple #22
0
/*	Insert new unique item to the `where` position in UniqueList. */
int
UniqueList_Insert(UniqueList *self, Py_ssize_t where, PyObject *newitem) {

	if (PyDict_Check(newitem) || PyList_Check(newitem) || PyTuple_Check(newitem)) {
		PyErr_SetString(PyExc_ValueError, "This type of list can not contain instances of Python tuple, list or dict.");
		return -1;
	}

	if (UniqueList_Contains(self, newitem) == 1) {
		PyErr_Format(PyExc_ValueError, "%R is already in the list.", newitem);
		return -1;
	}

    return PyList_Insert((PyObject *)self, where, newitem);
}
int main (int argc, char *argv[] ){
	const char *scriptDirectoryName = "./pyutils";
	
	Py_SetProgramName(argv[0]);
	PyObject *pName, *pModule, *pDict, *pFunc, *pValue, *presult;
	
	
	// Initialize the Python Interpreter
	Py_Initialize();
	PyObject *sysPath = PySys_GetObject("path");
	PyObject *path = PyString_FromString(scriptDirectoryName);
	int result = PyList_Insert(sysPath, 0, path);
	pModule = PyImport_ImportModule("arbName");
	if (PyErr_Occurred())
		PyErr_Print();
//	printf("%p\n", pModule);
	
	
	
	// pDict is a borrowed reference
	pDict = PyModule_GetDict(pModule);
	
	// pFunc is also a borrowed reference
	pFunc = PyDict_GetItemString(pDict, (char*)"someFunction");
	
	if (PyCallable_Check(pFunc))
	{
		pValue=Py_BuildValue("(z)",(char*)"something");
		PyErr_Print();
		printf("Let's give this a shot!\n");
		presult=PyObject_CallObject(pFunc,pValue);
		PyErr_Print();
	} else
	{
		PyErr_Print();
	}
	printf("Result is %ld\n", PyInt_AsLong(presult));
	Py_DECREF(pValue);
	
	// Clean up
	Py_DECREF(pModule);
	
	
	// Finish the Python Interpreter
	Py_Finalize();
	
	return 0;
}
Exemple #24
0
void addModuleSearchPath(const std::string& path)
{
    std::string pathString("path");
    auto syspath = PySys_GetObject(&pathString[0]); // Borrowed reference

    PythonObject pypath(PythonObject::owning {},
        PyString_FromString(path.c_str()));

    if (!pypath) {
        throw WrappyError("Wrappy: Can't allocate memory for string.");
    }

    auto pos = PyList_Insert(syspath, 0, pypath.get());
    if (pos < 0) {
        throw WrappyError("Wrappy: Couldn't add " + path + " to sys.path");
    }
}
/*
    Write a token to the current token stack.
*/
int Tokenizer_emit_token(Tokenizer* self, PyObject* token, int first)
{
    PyObject* instance;

    if (Tokenizer_push_textbuffer(self))
        return -1;
    instance = PyObject_CallObject(token, NULL);
    if (!instance)
        return -1;
    if (first ? PyList_Insert(self->topstack->stack, 0, instance) :
                PyList_Append(self->topstack->stack, instance)) {
        Py_DECREF(instance);
        return -1;
    }
    Py_DECREF(instance);
    return 0;
}
/*!
	Starts the python interpreter
*/
void startPython( int argc, char* argv[] )
{
	Py_SetProgramName( argv[0] );

	Py_NoSiteFlag = 1; // No import because we need to set the search path first

	Py_Initialize();
	PySys_SetArgv( argc, argv );

	// Modify our search-path
	PyObject* searchpath = PySys_GetObject( "path" );

	QStringList elements = QStringList::split( ";", Config::instance()->getString( "General", "Python Searchpath", "./scripts;.", true ) );

	// Prepend our items to the searchpath
	for ( int i = elements.count() - 1; i >= 0; --i )
	{
		PyList_Insert( searchpath, 0, PyString_FromString( elements[i].latin1() ) );
	}

	// Import site now
	PyObject* m = PyImport_ImportModule( "site" );
	Py_XDECREF( m );

	// Try changing the stderr + stdout pointers
	PyObject* file = PyFile_FromString( "python.log", "w" );

	if ( file )
	{
		Py_INCREF( file );
		PySys_SetObject( "stderr", file );
		Py_INCREF( file );
		PySys_SetObject( "stdout", file );
		Py_DECREF( file );
	}

	try
	{
		init_wolfpack_globals();
	}
	catch ( ... )
	{
		Console::instance()->send( "Failed to initialize the python extension modules\n" );
	}
}
Exemple #27
0
void set_dyn_pyhome(char *home, uint16_t pyhome_len) {


	char venv_version[15];
	PyObject *site_module;

	PyObject *pysys_dict = get_uwsgi_pydict("sys");

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

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

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

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

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

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

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

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

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

        }
}
Exemple #28
0
/* Expose the notices received as Python objects.
 *
 * The function should be called with the connection lock and the GIL.
 */
void
conn_notice_process(connectionObject *self)
{
    struct connectionObject_notice *notice;
    Py_ssize_t nnotices;

    if (NULL == self->notice_pending) {
        return;
    }

    notice =  self->notice_pending;
    nnotices = PyList_GET_SIZE(self->notice_list);

    while (notice != NULL) {
        PyObject *msg;
        msg = conn_text_from_chars(self, notice->message);
        Dprintf("conn_notice_process: %s", notice->message);

        /* Respect the order in which notices were produced,
           because in notice_list they are reversed (see ticket #9) */
        if (msg) {
            PyList_Insert(self->notice_list, nnotices, msg);
            Py_DECREF(msg);
        }
        else {
            /* We don't really have a way to report errors, so gulp it.
             * The function should only fail for out of memory, so we are
             * likely going to die anyway. */
            PyErr_Clear();
        }

        notice = notice->next;
    }

    /* Remove the oldest item if the queue is getting too long. */
    nnotices = PyList_GET_SIZE(self->notice_list);
    if (nnotices > CONN_NOTICES_LIMIT) {
        PySequence_DelSlice(self->notice_list,
            0, nnotices - CONN_NOTICES_LIMIT);
    }

    conn_notice_clean(self);
}
Exemple #29
0
bool CPythonEngine::AddToPythonPath(LPCTSTR pPathName)
{
	PyObject *obPathList = PySys_GetObject("path");
	if (obPathList==NULL) {
		return false;
	}

	// Some pathnames have a leading '\\?\', which tells allows Unicode
	// win32 functions to avoid MAX_PATH limitations.  Notably,
	// GetModulePath for our extension DLL may - presumably as such a
	// path was specified by IIS when loading the DLL.
	// Current Python versions handle neither this, nor Unicode on
	// sys.path, so correct this here.
	size_t len = _tcslen(pPathName);
	if (len > 4 && _tcsncmp(pPathName, _T("\\\\?\\"), 4)==0) {
		pPathName += 4;
		len -= 4;
	}
#if (PY_VERSION_HEX < 0x03000000)
	PyObject *obNew = PyString_FromStringAndSize(pPathName, len);
#else
	PyObject *obNew = PyUnicode_FromWideChar(pPathName, len);
#endif
	if (obNew==NULL) {
		return false;
	}

	bool bFnd=false;
	for (int i=0; i<PyList_Size(obPathList); i++){
		PyObject * obItem = PyList_GetItem(obPathList, i);
		if(PyObject_RichCompare(obNew, obItem, Py_EQ) == Py_True){
			bFnd = true;
			break;
		}
	}

	if (!bFnd)
		PyList_Insert(obPathList, 0, obNew);

	Py_XDECREF(obNew);
	return true;
}
static PyObject *Scopeable_push(PyObject *self, PyObject *args) {
  PyObject *newDict, *dictList;
  if (!PyArg_ParseTuple(args, "OO", &self, &newDict)) {
    return NULL;
  }
  if (!PyDict_Check(newDict)) {
    PyErr_SetString(PyExc_TypeError, "push() requires a dictionary argument");
    return NULL;
  }
  dictList=PyMapping_GetItemString(((PyInstanceObject *)self)->in_dict, DICTLIST);
  if (!PyList_Check(dictList)) {
    PyErr_SetString(PyExc_TypeError, "expected list for dictList!");
    Py_XDECREF(dictList);
    return NULL;
  }
  PyList_Insert(dictList, 0, newDict); 
  Py_DECREF(dictList);
  Py_INCREF(Py_None);
  return Py_None;
}