示例#1
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
}
示例#2
0
文件: sys.cpp 项目: xujun10110/pyston
static void mywrite(const char* name, FILE* fp, const char* format, va_list va) noexcept {
    PyObject* file;
    PyObject* error_type, *error_value, *error_traceback;

    PyErr_Fetch(&error_type, &error_value, &error_traceback);
    file = PySys_GetObject(name);
    if (file == NULL || PyFile_AsFile(file) == fp)
        vfprintf(fp, format, va);
    else {
        char buffer[1001];
        const int written = PyOS_vsnprintf(buffer, sizeof(buffer), format, va);
        if (PyFile_WriteString(buffer, file) != 0) {
            PyErr_Clear();
            fputs(buffer, fp);
        }
        if (written < 0 || (size_t)written >= sizeof(buffer)) {
            const char* truncated = "... truncated";
            if (PyFile_WriteString(truncated, file) != 0) {
                PyErr_Clear();
                fputs(truncated, fp);
            }
        }
    }
    PyErr_Restore(error_type, error_value, error_traceback);
}
示例#3
0
文件: r_print.c 项目: jwilk/Pyrex
static PyObject *__Pyx_GetStdout(void) {
	PyObject *f = PySys_GetObject("stdout");
	if (!f) {
		PyErr_SetString(PyExc_RuntimeError, "lost sys.stdout");
	}
	return f;
}
示例#4
0
PyMODINIT_FUNC
PyOtherSide_init()
{
    PyObject *pyotherside = PyModule_Create(&PyOtherSideModule);

    // Format constants for the image provider return value format
    // see http://qt-project.org/doc/qt-5.1/qtgui/qimage.html#Format-enum
    PyModule_AddIntConstant(pyotherside, "format_mono", QImage::Format_Mono);
    PyModule_AddIntConstant(pyotherside, "format_mono_lsb", QImage::Format_MonoLSB);
    PyModule_AddIntConstant(pyotherside, "format_rgb32", QImage::Format_RGB32);
    PyModule_AddIntConstant(pyotherside, "format_argb32", QImage::Format_ARGB32);
    PyModule_AddIntConstant(pyotherside, "format_rgb16", QImage::Format_RGB16);
    PyModule_AddIntConstant(pyotherside, "format_rgb666", QImage::Format_RGB666);
    PyModule_AddIntConstant(pyotherside, "format_rgb555", QImage::Format_RGB555);
    PyModule_AddIntConstant(pyotherside, "format_rgb888", QImage::Format_RGB888);
    PyModule_AddIntConstant(pyotherside, "format_rgb444", QImage::Format_RGB444);

    // Custom constant - pixels are to be interpreted as encoded image file data
    PyModule_AddIntConstant(pyotherside, "format_data", -1);

    PyObject *meta_path = PySys_GetObject("meta_path");
    if (meta_path != NULL)
    {
        PyList_Append(meta_path, pyotherside);
    }

    return pyotherside;
}
示例#5
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("Failed to create Unicode object");
		return SRD_ERR_PYTHON;
	}
	if (PyList_Insert(py_cur_path, 0, py_item) < 0) {
		srd_exception_catch("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;
}
示例#6
0
PyObject *set_stdstream(std::string name, PyObject *pystream) {
  PyObject *old_pystream = PySys_GetObject(const_cast<char*>(name.c_str())); // borrowed
  Py_XINCREF(pystream);
  PySys_SetObject(const_cast<char*>(name.c_str()), pystream);
  Py_XDECREF(old_pystream);
  return old_pystream;
}
示例#7
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();
}
示例#8
0
文件: local.c 项目: chenbk85/jega
PyObject* 
init_local_module(PyObject *m)
{
    PyObject *d, *sd, *v;
    PyObject *sys_modules, *module;
    PyMethodDef *ml;
    

#ifdef PY3
    PyObject *mod_name = PyUnicode_FromString(MODULE_NAME "." LOCAL_MOD_NAME);
#else
    PyObject *mod_name = PyBytes_FromString(MODULE_NAME "." LOCAL_MOD_NAME);
#endif
    
    if(mod_name == NULL){
        return NULL;
    }

    LocalObjectType.tp_new = PyType_GenericNew;
    if(PyType_Ready(&LocalObjectType) < 0){
        return NULL;
    }

    sys_modules = PySys_GetObject("modules");
    d = PyModule_GetDict(m);
    module = PyDict_GetItem(d, mod_name);
    if(module == NULL) {
        module = PyModule_New(MODULE_NAME "." LOCAL_MOD_NAME);
        if(module != NULL) {
            PyDict_SetItem(sys_modules, mod_name, module);
            PyModule_AddObject(m, LOCAL_MOD_NAME, module);
        }
    }
    sd = PyModule_GetDict(module);
    for(ml = LocalMod_methods; ml->ml_name != NULL; ml++){
        v = PyCFunction_NewEx(ml, (PyObject *)NULL, mod_name);
        if(v == NULL) {
            goto fin;
        }
        if(PyDict_SetItemString(sd, ml->ml_name, v) != 0){
            Py_DECREF(v);
            return NULL;
        }
        Py_DECREF(v);
    }

fin:
    Py_DECREF(mod_name);

    Py_INCREF(&LocalObjectType);
    PyModule_AddObject(module, "local", (PyObject *)&LocalObjectType);
    
#ifdef PY3
    dict_key = PyUnicode_FromString("_jega_local_dict__");
#else
    dict_key = PyBytes_FromString("_jega_local_dict__");
#endif
    return module;
}
示例#9
0
void python_script_error_jump(const char *filepath, int *lineno, int *offset)
{
  PyObject *exception, *value;
  PyTracebackObject *tb;

  *lineno = -1;
  *offset = 0;

  PyErr_Fetch(&exception, &value, (PyObject **)&tb);

  if (exception && PyErr_GivenExceptionMatches(exception, PyExc_SyntaxError)) {
    /* no traceback available when SyntaxError.
     * python has no api's to this. reference parse_syntax_error() from pythonrun.c */
    PyErr_NormalizeException(&exception, &value, (PyObject **)&tb);
    PyErr_Restore(exception, value, (PyObject *)tb); /* takes away reference! */

    if (value) { /* should always be true */
      PyObject *message;
      PyObject *filename_py, *text_py;

      if (parse_syntax_error(value, &message, &filename_py, lineno, offset, &text_py)) {
        const char *filename = _PyUnicode_AsString(filename_py);
        /* python adds a '/', prefix, so check for both */
        if ((BLI_path_cmp(filename, filepath) == 0) ||
            ((filename[0] == '\\' || filename[0] == '/') &&
             BLI_path_cmp(filename + 1, filepath) == 0)) {
          /* good */
        }
        else {
          *lineno = -1;
        }
      }
      else {
        *lineno = -1;
      }
    }
  }
  else {
    PyErr_NormalizeException(&exception, &value, (PyObject **)&tb);
    PyErr_Restore(exception, value, (PyObject *)tb); /* takes away reference! */
    PyErr_Print();

    for (tb = (PyTracebackObject *)PySys_GetObject("last_traceback");
         tb && (PyObject *)tb != Py_None;
         tb = tb->tb_next) {
      PyObject *coerce;
      const char *tb_filepath = traceback_filepath(tb, &coerce);
      const int match = ((BLI_path_cmp(tb_filepath, filepath) == 0) ||
                         ((tb_filepath[0] == '\\' || tb_filepath[0] == '/') &&
                          BLI_path_cmp(tb_filepath + 1, filepath) == 0));
      Py_DECREF(coerce);

      if (match) {
        *lineno = tb->tb_lineno;
        /* used to break here, but better find the inner most line */
      }
    }
  }
}
示例#10
0
  python_bridge_guard(){
    Py_Initialize();

    PyObject* sysPath = PySys_GetObject((char*)"path");
    PyObject* curDir = PyString_FromString(".");
    PyList_Append(sysPath, curDir);
    Py_DECREF(curDir);
  }
示例#11
0
 PythonRedirector(const char* type, PyObject* obj) : std_out(type), out(obj), old(0)
 {
     if (out) {
         Base::PyGILStateLocker lock;
         old = PySys_GetObject(const_cast<char*>(std_out));
         PySys_SetObject(const_cast<char*>(std_out), out);
     }
 }
示例#12
0
		CPyInstance() {
			Py_Initialize();

			// Add current dir to system path
			PyObject* sysPath = PySys_GetObject((char*)"path");
			PyList_Append(sysPath, PyString_FromString("."));

		}
示例#13
0
/*
* Method to call TUFs configure method. This function takes the JSON interposition filename
* as well as the parent repository directory and the parent ssl certificate directory, and
* configures TUF to interpose on update calls
*/
bool Py_TUF_configure(char* tuf_intrp_json, char* p_repo_dir, char* p_ssl_cert_dir) {
//PyObject* Py_TUF_configure(char* tuf_intrp_json, char* p_repo_dir, char* p_ssl_cert_dir){
    // Init the python env
    Py_Initialize();

	//add the current directory to the places to search for TUF
	PyObject *path = PySys_GetObject( (char *)"path" );
	PyObject *currentDirectory = PyString_FromString( "." );
	PyList_Append( path, currentDirectory );
	Py_XDECREF( currentDirectory );

	//import TUF module
	PyObject *moduleName = PyString_FromString( "tuf.interposition" );
	PyObject *tufInterMod = PyImport_Import( moduleName );
	if ( tufInterMod == NULL ) {
		PyErr_Print();
		return false;
	}
	Py_XDECREF( moduleName );
	
	//get the configure function from tuf.interposition
	PyObject *configFunction = PyObject_GetAttrString( tufInterMod, "configure" );
	if ( configFunction == NULL ) {
		PyErr_Print();
		return false;
	}
	Py_XDECREF( tufInterMod );
	
	//convert arguements into Python types and create tuple for CallObject function
	PyObject *args = PyTuple_New( 3 );
    PyObject *arg0 = PyString_FromString( tuf_intrp_json );
    PyTuple_SetItem(args, 0, arg0);
    PyObject *arg1 = PyString_FromString( p_repo_dir );
    PyTuple_SetItem(args, 1, arg1);
    PyObject *arg2 = PyString_FromString( p_ssl_cert_dir );
    PyTuple_SetItem(args, 2, arg2);

	//calls the config function from the tuf.interposition module
	//returns a dictionary with the configurations	
	//we are currently storing this globally 	
	configDict = PyObject_CallObject( configFunction, args );

	//Py_XDECREF( arg0 );
	//Py_XDECREF( arg1 );
	//Py_XDECREF( arg2 );
	//Py_XDECREF( args );
	//Py_XDECREF( configFunction );

	if ( configDict == NULL ) {
		PyErr_Print();
		return false;
	}


	printf( "TUF configured.\n" );
	return true;
	//return configDict;
}
示例#14
0
static int
tok_stdin_decode(struct tok_state *tok, char **inp)
{
	PyObject *enc, *sysstdin, *decoded, *utf8;
	const char *encoding;
	char *converted;

	if (PySys_GetFile((char *)"stdin", NULL) != stdin)
		return 0;
	sysstdin = PySys_GetObject("stdin");
	if (sysstdin == NULL || !PyFile_Check(sysstdin))
		return 0;

	enc = ((PyFileObject *)sysstdin)->f_encoding;
	if (enc == NULL || !PyString_Check(enc))
		return 0;
	Py_INCREF(enc);

	encoding = PyString_AsString(enc);
	decoded = PyUnicode_Decode(*inp, strlen(*inp), 0, encoding, NULL);
	if (decoded == NULL)
		goto error_clear;

	utf8 = PyUnicode_AsEncodedString(decoded, "utf-8", NULL);
	Py_DECREF(decoded);
	if (utf8 == NULL)
		goto error_clear;

	assert(PyString_Check(utf8));
	converted = new_string(PyString_AS_STRING(utf8),
			       PyString_GET_SIZE(utf8));
	Py_DECREF(utf8);
	if (converted == NULL)
		goto error_nomem;

	PyMem_FREE(*inp);
	*inp = converted;
	if (tok->encoding != NULL)
		PyMem_FREE(tok->encoding);
	tok->encoding = new_string(encoding, strlen(encoding));
	if (tok->encoding == NULL)
		goto error_nomem;

	Py_DECREF(enc);
	return 0;

error_nomem:
	Py_DECREF(enc);
	tok->done = E_NOMEM;
	return -1;

error_clear:
	/* Fallback to iso-8859-1: for backward compatibility */
	Py_DECREF(enc);
	PyErr_Clear();
	return 0;
}
示例#15
0
/* Add to the list of script load paths */
void pyloader_add_script_path(const char *path)
{
    PyObject *ppath = PySys_GetObject("path");
    if (ppath)
    {
        PyList_Append(ppath, PyString_FromString(path));
        script_paths = g_slist_append(script_paths, g_strdup(path));
    }
}
示例#16
0
文件: sys.cpp 项目: Thooms/pyston
extern "C" FILE* PySys_GetFile(char* name, FILE* def) noexcept {
    FILE* fp = NULL;
    PyObject* v = PySys_GetObject(name);
    if (v != NULL && PyFile_Check(v))
        fp = PyFile_AsFile(v);
    if (fp == NULL)
        fp = def;
    return fp;
}
示例#17
0
文件: Geometry.c 项目: jinjoh/NOOR
/*----------------------------MODULE INIT-------------------------*/
PyObject *Geometry_Init(void)
{
	PyObject *submodule;
	
	submodule = PyModule_Create(&M_Geometry_module_def);
	PyDict_SetItemString(PySys_GetObject("modules"), M_Geometry_module_def.m_name, submodule);
	
	return (submodule);
}
示例#18
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;
}
示例#19
0
文件: errors.c 项目: irov/Mengine
/* Call when an exception has occurred but there is no way for Python
   to handle it.  Examples: exception in __del__ or during GC. */
void
PyErr_WriteUnraisable(PyObject *obj)
{
    PyObject *f, *t, *v, *tb;
    PyErr_Fetch(&t, &v, &tb);
    f = PySys_GetObject("stderr");
    if (f != NULL) {
        PyFile_WriteString("Exception ", f);
        if (t) {
            PyObject* moduleName;
            char* className;
            assert(PyExceptionClass_Check(t));
            className = PyExceptionClass_Name(t);
            if (className != NULL) {
                char *dot = strrchr(className, '.');
                if (dot != NULL)
                    className = dot+1;
            }

            moduleName = PyObject_GetAttrString(t, "__module__");
            if (moduleName == NULL)
                PyFile_WriteString("<unknown>", f);
            else {
                char* modstr = PyString_AsString(moduleName);
                if (modstr &&
                    strcmp(modstr, "exceptions") != 0)
                {
                    PyFile_WriteString(modstr, f);
                    PyFile_WriteString(".", f);
                }
            }
            if (className == NULL)
                PyFile_WriteString("<unknown>", f);
            else
                PyFile_WriteString(className, f);
            if (v && v != Py_None) {
                PyFile_WriteString(": ", f);
                if (PyFile_WriteObject(v, f, 0) < 0) {
                    PyErr_Clear();
                    PyFile_WriteString("<exception repr() failed>", f);
                }
            }
            Py_XDECREF(moduleName);
        }
        PyFile_WriteString(" in ", f);
        if (PyFile_WriteObject(obj, f, 0) < 0) {
            PyErr_Clear();
            PyFile_WriteString("<object repr() failed>", f);
        }
        PyFile_WriteString(" ignored\n", f);
        PyErr_Clear(); /* Just in case */
    }
    Py_XDECREF(t);
    Py_XDECREF(v);
    Py_XDECREF(tb);
}
示例#20
0
文件: GenPy.cpp 项目: kbochenina/Snap
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");
}
示例#21
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);
}
示例#22
0
void Redirector::set_stdout(stdout_write_type write)
{
    if (!m_stdout)
    {
        m_stdout_saved = PySys_GetObject(const_cast<char*>("stdout")); // borrowed
        m_stdout = StdoutType.tp_new(&StdoutType, 0, 0);
    }

    Stdout* impl = reinterpret_cast<Stdout*>(m_stdout);
    impl->write = write;
    PySys_SetObject(const_cast<char*>("stdout"), m_stdout);
}
示例#23
0
void ssipylog_stdout_set(ssipylog_stdout_write_type write)
{
    if (!ssipylog_g_stdout)
    {
		ssipylog_g_stdout_saved = PySys_GetObject("stdout"); // borrowed
		ssipylog_g_stdout = ssipylog_stdout_Type.tp_new(&ssipylog_stdout_Type, 0, 0);
    }

	ssipylog_stdout *impl = (ssipylog_stdout *)ssipylog_g_stdout;
    impl->write = write;
    PySys_SetObject("stdout", ssipylog_g_stdout);
}
示例#24
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;
		}
    }
示例#25
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.
 */
SRD_PRIV int srd_decoder_searchpath_add(const char *path)
{
	PyObject *py_cur_path, *py_item;
	GString *new_path;
	int wc_len, i;
	wchar_t *wc_new_path;
	char *item;

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

	new_path = g_string_sized_new(256);
	g_string_assign(new_path, g_strdup(path));
	py_cur_path = PySys_GetObject("path");
	for (i = 0; i < PyList_Size(py_cur_path); i++) {
		g_string_append(new_path, g_strdup(G_SEARCHPATH_SEPARATOR_S));
		py_item = PyList_GetItem(py_cur_path, i);
		if (!PyUnicode_Check(py_item))
			/* Shouldn't happen. */
			continue;
		if (py_str_as_str(py_item, &item) != SRD_OK)
			continue;
		g_string_append(new_path, item);
	}

	/* Convert to wide chars. */
	wc_len = sizeof(wchar_t) * (new_path->len + 1);
	if (!(wc_new_path = g_try_malloc(wc_len))) {
		srd_dbg("malloc failed");
		return SRD_ERR_MALLOC;
	}
	mbstowcs(wc_new_path, new_path->str, wc_len);
	PySys_SetPath(wc_new_path);
	g_string_free(new_path, TRUE);
	g_free(wc_new_path);

//#ifdef _WIN32
//	gchar **splitted;
//
//	/*
//	 * On Windows/MinGW, Python's sys.path needs entries of the form
//	 * 'C:\\foo\\bar' instead of '/foo/bar'.
//	 */
//
//	splitted = g_strsplit(DECODERS_DIR, "/", 0);
//	path = g_build_pathv("\\\\", splitted);
//	g_strfreev(splitted);
//#else
//	path = g_strdup(DECODERS_DIR);
//#endif

	return SRD_OK;
}
int
_Py_DisplaySourceLine(PyObject *f, const char *filename, int lineno, int indent)
{
    int err = 0;
    FILE *xfp = NULL;
    char linebuf[2000];
    int i;
    char namebuf[MAXPATHLEN+1];

    if (filename == NULL)
        return -1;
    /* This is needed by Emacs' compile command */
#define FMT "  File \"%.500s\", line %d, in %.500s\n"
    xfp = fopen(filename, "r" PY_STDIOTEXTMODE);
    if (xfp == NULL) {
        /* Search tail of filename in sys.path before giving up */
        PyObject *path;
        const char *tail = strrchr(filename, SEP);
        if (tail == NULL)
            tail = filename;
        else
            tail++;
        path = PySys_GetObject("path");
        if (path != NULL && PyList_Check(path)) {
            Py_ssize_t _npath = PyList_Size(path);
            int npath = Py_SAFE_DOWNCAST(_npath, Py_ssize_t, int);
            size_t taillen = strlen(tail);
            for (i = 0; i < npath; i++) {
                PyObject *v = PyList_GetItem(path, i);
                if (v == NULL) {
                    PyErr_Clear();
                    break;
                }
                if (PyString_Check(v)) {
                    size_t len;
                    len = PyString_GET_SIZE(v);
                    if (len + 1 + taillen >= MAXPATHLEN)
                        continue; /* Too long */
                    strcpy(namebuf, PyString_AsString(v));
                    if (strlen(namebuf) != len)
                        continue; /* v contains '\0' */
                    if (len > 0 && namebuf[len-1] != SEP)
                        namebuf[len++] = SEP;
                    strcpy(namebuf+len, tail);
                    xfp = fopen(namebuf, "r" PY_STDIOTEXTMODE);
                    if (xfp != NULL) {
                        filename = namebuf;
                        break;
                    }
                }
            }
        }
/** Helper to verify current reference count and avoid memory leaks */
size_t PythonTotalRefCount()
{
#ifdef Py_DEBUG
	#pragma message("Open3DMotion MESSAGE: Debug build selected. Ensure that a custom build of python shared library is used (one built with Py_DEBUG defined).")
	PyObject* borrowed_count_function = PySys_GetObject("gettotalrefcount");
	PyObject* py_count = PyObject_CallObject(borrowed_count_function, NULL);
  size_t count = PyInt_AsSsize_t(py_count);
  Py_DECREF(py_count);
	return count;
#else
	return 0;
#endif
}
示例#28
0
文件: Python.cpp 项目: zzydog/OllyDog
int CPython::ExecEcho(const std::wstring &cmds, std::wstring &err, HANDLE hfile)
{
	int id = 0; FILE *pfile = nullptr; DWORD count = 0;
	PyObject *poldout, *polderr, *pnewout, *pnewerr; 
	if (cmds.length() <= 0) {
		err = text("No python command found"); return 1;
	}
	if (DuplicateHandle ( 
		GetCurrentProcess(), hfile, GetCurrentProcess(), &hfile, 
		0, false, DUPLICATE_SAME_ACCESS 
	)) { 
		id = open_osfhandle((intptr_t)hfile, _O_WRONLY); 
		pfile = fdopen(id,"w"); setvbuf(pfile,nullptr,_IONBF,1024); 
		poldout = PySys_GetObject("stdout"); 
		polderr = PySys_GetObject("stderr"); 
		pnewout = PyFile_FromFile(pfile, "logger", "w", nullptr); 
		pnewerr = PyFile_FromFile(pfile, "logger", "w", nullptr); 
		PySys_SetObject("stdout", pnewout); 
		PySys_SetObject("stderr", pnewerr); 
	} else poldout = polderr = pnewout = pnewerr = nullptr; 

	std::wstring_convert<std::codecvt_utf8_utf16<wchar>> cvt; 
	std::string str = cvt.to_bytes(cmds); 
	std::size_t pos = str.find(text('.')); 
	if (pos != std::string::npos) { 
		std::string mod = str.substr(0, pos); 
		PyObject* dest = PyImport_ImportModule(mod.c_str()); 
		PyObject* main = PyImport_AddModule("__main__"); 
		PyObject_SetAttrString(main, mod.c_str(), dest); 
	} 
	str.insert(0, "print ");
	int irslt = PyRun_SimpleString(str.c_str());
	if (irslt != 0) err = text("Internal error that PyRun_SimpleString fail"); 
	else err = text("Execute python expression successfully .."); 

	if (pnewout != nullptr) PySys_SetObject("stdout", poldout); 
	if (pnewerr != nullptr) PySys_SetObject("stderr", polderr); 
	if (pfile != nullptr) fclose(pfile); return irslt; 
}
示例#29
0
static void
call_sys_exitfunc(void)
{
	PyObject *exitfunc = PySys_GetObject("exitfunc");

	if (exitfunc) {
		PyObject *res, *f;
		Py_INCREF(exitfunc);
		PySys_SetObject("exitfunc", (PyObject *)NULL);
		f = PySys_GetObject("stderr");
		res = PyEval_CallObject(exitfunc, (PyObject *)NULL);
		if (res == NULL) {
			if (f)
			    PyFile_WriteString("Error in sys.exitfunc:\n", f);
			PyErr_Print();
		}
		Py_DECREF(exitfunc);
	}

	if (Py_FlushLine())
		PyErr_Clear();
}
示例#30
0
//-------------------------------------------------------------------------------------
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;
}