static void check_init() {
    if ((initialized == 0) && ! Py_IsInitialized()) {
        Py_Initialize();
        #ifdef _WIN32
        PyRun_SimpleString(pCleanPath);
        #endif
        initialized = 1;
    }
}
Exemplo n.º 2
0
// Run a thread to manage a console-based interpreter
void ConsoleClass::pyconsole(){
	std::string input, subinput;
	bool outputting;

	// Register python output to std streams
	registerStdout(&std::cout);
	registerStderr(&std::cerr);

	while (true)
	{
		outputting = true;
		// This could be replaced with pythons sys.ps1
		std::cout << ">>> ";

		// Reset stdin to deal with ctrl-c
		// This needs actual handling later
		std::cin.clear();

		std::getline(std::cin, input);
		// Handling for structures (if, while, def, etc)
		if (input[input.length()-1] == ':')
		{
			outputting = false;
			while (true)
			{
				// This could be replaced with pythons sys.ps2
				std::cout << "... ";
				std::getline(std::cin, subinput);
				// When we get an empty line we are ready to run the input
				if (subinput.length() == 0) break;
				input += "\n" + subinput;
			}
		}

		// TODO process ; delimited statements?

		// Don't run empty input
		if (input.length() == 0) continue;

		// Aesthetics
		input += "\n";
		
		// Send to anyone listening for evaluated scripts
		python_evaluator.Write(">>>" + input);

		// These strings mean we won't get return/output, there are probably more
		if (input.find("import") != std::string::npos) outputting = false;
		if (input.find("print") != std::string::npos) outputting = false;
		if (input.find("=") != std::string::npos) outputting = false;

		// This is probably wrong
		if (outputting)
			input = "print " + input;
		
		PyRun_SimpleString((char*)input.c_str());
	}
}
Exemplo n.º 3
0
int main(int argc, char *argv[])
{
    Py_SetProgramName(argv[0]);  /* optional but recommended */
    Py_Initialize();
    PyRun_SimpleString("from time import time,ctime\n"
                       "print 'Today is',ctime(time())\n");
    Py_Finalize();
    return 0;
}
Exemplo n.º 4
0
Arquivo: embed.c Projeto: i-wind/pymix
int
main(int argc, char *argv[])
{
    Py_SetProgramName(argv[0]);  /* optional but recommended */
    Py_Initialize();

    numargs = argc;
    Py_InitModule("emb", EmbMethods);

    PyRun_SimpleString("from time import time, ctime\n"
                       "print 'Today is', ctime(time())\n");

    PyRun_SimpleString("import emb\n"
                       "print 'Number of arguments', emb.numargs()\n");

    Py_Finalize();
    return 0;
}
Exemplo n.º 5
0
void
python_check_error(void)
{
    if (PyErr_Occurred()) {
        PyErr_Print();
        PyRun_SimpleString("import sys\nsys.stdout.flush()");
        PyErr_Clear();
    }
}
Exemplo n.º 6
0
PyMODINIT_FUNC script_init_mudmagic(void) {
	PyObject * p_main;

	PyImport_AddModule ("mudmagic");
	Py_InitModule ("mudmagic", MudmagicMethods);
	p_main = PyImport_AddModule ("__main__");
	p_main_dict = PyModule_GetDict (p_main);
	PyRun_SimpleString("from mudmagic import *\n");
}
Exemplo n.º 7
0
bool Pythonize::runString (char *str)
{

    if (str == NULL || strlen (str) == 0) return false;

    int res = PyRun_SimpleString (str);

    return res == 0;
}
Exemplo n.º 8
0
int main(int argc, char **argv) {
  Py_SetProgramName(argv[0]);  /* optional but recommended */
  Py_Initialize();
  PyRun_SimpleString("from time import time,ctime\n"
                     "print 'Today is',ctime(time())\n");
  // or use PyRun_SimpleFile(FILE *fp, const char *filename) to run a program file
  Py_Finalize();
  return 0;
}
Exemplo n.º 9
0
void PyModule::printInfo() {
    for (auto& elem : methods_) {
        std::string msg = "print(\"";
        msg += elem->getName() + ":\t";
        msg += elem->getDesc();
        msg += "\")\n";
        PyRun_SimpleString(msg.c_str());
    }
}
Exemplo n.º 10
0
void init_script(const char *exe_path)
{
  exe_dir=QFileInfo(exe_path).absoluteDir();

  qDebug() << "prog name:" << exe_path;
  Py_SetProgramName((char*)exe_path);

  qDebug() << "init py...";
  Py_Initialize();
  qDebug() << "init py ok";

  init_python_console();
  init_sproxel_bindings();

  pycon("exe path: %s", exe_path);
  pycon("exe dir: %s", exe_dir.absolutePath().toLocal8Bit().data());

  QString code="import sys\nsys.path.insert(0, \"";
  code.append(exe_dir.absolutePath());
  code.append("\")\nprint 'sys.path:', sys.path\n");
  PyRun_SimpleString(code.toLocal8Bit().data());

  PyObject *mod=PyImport_ImportModule("sproxel_utils");
  if (!mod)
  {
    PyErr_Print();
    QMessageBox::critical(NULL, "Sproxel Error", "Failed to import sproxel_utils");
  }
  else
  {
    // check required methods
    bool gotErrors=false;

    py_save_project=PyObject_GetAttrString(mod, "save_project");
    if (PyErr_Occurred()) { PyErr_Print(); gotErrors=true; }

    py_load_project=PyObject_GetAttrString(mod, "load_project");
    if (PyErr_Occurred()) { PyErr_Print(); gotErrors=true; }

    py_init_plugin_pathes=PyObject_GetAttrString(mod, "init_plugin_pathes");
    if (PyErr_Occurred()) { PyErr_Print(); gotErrors=true; }

    py_scan_plugins=PyObject_GetAttrString(mod, "scan_plugins");
    if (PyErr_Occurred()) { PyErr_Print(); gotErrors=true; }

    py_register_plugins=PyObject_GetAttrString(mod, "register_plugins");
    if (PyErr_Occurred()) { PyErr_Print(); gotErrors=true; }

    py_unregister_plugins=PyObject_GetAttrString(mod, "unregister_plugins");
    if (PyErr_Occurred()) { PyErr_Print(); gotErrors=true; }

    pycon("Scripted methods: %s", gotErrors ? "some missing" : "all OK");
    if (gotErrors) QMessageBox::critical(NULL, "Sproxel Error", "Some scripted methods are missing.");

    Py_DECREF(mod); mod=NULL;
  }
}
Exemplo n.º 11
0
Arquivo: if_python.c Projeto: aosm/vim
    static int
Python_Init(void)
{
    if (!initialised)
    {
#ifdef DYNAMIC_PYTHON
	if (!python_enabled(TRUE))
	{
	    EMSG(_("E263: Sorry, this command is disabled, the Python library could not be loaded."));
	    goto fail;
	}
#endif

	init_structs();

#if !defined(MACOS) || defined(MACOS_X_UNIX)
	Py_Initialize();
#else
	PyMac_Initialize();
#endif
	/* initialise threads */
	PyEval_InitThreads();

#ifdef DYNAMIC_PYTHON
	get_exceptions();
#endif

	if (PythonIO_Init())
	    goto fail;

	if (PythonMod_Init())
	    goto fail;

	/* Remove the element from sys.path that was added because of our
	 * argv[0] value in PythonMod_Init().  Previously we used an empty
	 * string, but dependinding on the OS we then get an empty entry or
	 * the current directory in sys.path. */
	PyRun_SimpleString("import sys; sys.path = filter(lambda x: x != '/must>not&exist', sys.path)");

	/* the first python thread is vim's, release the lock */
	Python_SaveThread();

	initialised = 1;
    }

    return 0;

fail:
    /* We call PythonIO_Flush() here to print any Python errors.
     * This is OK, as it is possible to call this function even
     * if PythonIO_Init() has not completed successfully (it will
     * not do anything in this case).
     */
    PythonIO_Flush();
    return -1;
}
Exemplo n.º 12
0
BOOL OllyPython_Init(void)
{
    char initfile[MAX_PATH];
    char tmp[MAX_PATH+16];
    BOOL result = 1;

    if (initialized == 1)
    {
        return TRUE;
    }

    Addtolist(0, 0, "OllyPython");

    result &= CheckFile("init.py");
    result &= CheckFile("ollyapi.py");
    result &= CheckFile("ollyutils.py");

    if (!result)
    {
        Addtolist(0, -1, "  Could not locate Python scripts");
        return FALSE;
    }

    Py_Initialize();

    if (!Py_IsInitialized())
    {
        Addtolist(0, -1, "  Could not initialize Python");
        return FALSE;
    }

    init_ollyapi();

    GetModuleFileName(hinst, initfile, MAX_PATH);
    PathRemoveFileSpec(initfile);
    strncat(initfile, "\\python", 7);

    snprintf(tmp, MAX_PATH+16, "OLLYPYTHON_PATH=\"%s\"", initfile);
    PyRun_SimpleString(tmp);

    strncat(initfile, "\\init.py", 8);

    if (!ExecFile(initfile))
    {
        Addtolist(0, -1, "  Could not run init.py");
        return FALSE;
    }

#ifdef ENABLE_PYTHON_PROFILING
    PyEval_SetTrace(tracefunc, NULL);
#endif

    initialized = 1;

    return TRUE;
}
Exemplo n.º 13
0
int main() {
   PyObject *globals, *foo, *bar, *noargs, *ret;
   Py_Initialize();
   PyRun_SimpleString(
      "def foo(): \n"
      "   return 2, 10 \n"
      "def bar(): \n"
      "   return \n"
      "def teste(a,b): \n"
      "   print a, b \n"
      "   return 42 \n"
   );
   globals = PyModule_GetDict(PyImport_AddModule("__main__"));
   Py_INCREF(globals);
   
   static PyMethodDef teste_def[] = {{ "teste", (PyCFunction) teste, METH_VARARGS, NULL }};
   PyObject* teste_obj = Py_FindMethod(teste_def, NULL, "teste");
   PyDict_SetItemString(globals, "teste", teste_obj);
   
   PyObject *teste = PyDict_GetItemString(globals, "teste");
   PyObject *obj_result = PyObject_CallFunction(teste, "si", "entrada", 2);
   if (!obj_result) {
      return;
   }
   long result = PyInt_AsLong(obj_result);
   Py_DECREF(obj_result);
   printf("teste returned %ld \n", result);
   
   foo = PyDict_GetItemString(globals, "foo");
   noargs = PyTuple_New(0);
   ret = PyObject_Call(foo, noargs, NULL);
   printf("foo returned (%d, %d)\n", PyInt_AsLong(PyTuple_GET_ITEM(ret, 0)),
                                     PyInt_AsLong(PyTuple_GET_ITEM(ret, 1)));
   bar = PyDict_GetItemString(globals, "bar");
   Py_DECREF(ret);
   ret = PyObject_Call(bar, noargs, NULL);
   if (ret == Py_None) printf("bar returned Py_None\n");
   Py_DECREF(ret);
   Py_DECREF(noargs);
   Py_DECREF(globals);

   PyObject* s = PyString_FromString("hello world");

   PyObject* split = PyObject_GetAttrString(s, "split");
   ret = PyObject_CallFunction(split, "s", " ");
   /*
   ret = PyObject_CallMethod(s, "split", "s", " ");
   */
   int i;
   for (i = 0; i < PyList_GET_SIZE(ret); i++) {
      PyObject* item = PyList_GetItem(ret, i);
      printf("%d: '%s'\n", i, PyString_AsString(item));
   }

   Py_Finalize();
}
void Python_group_script::execute(const std::string grid_name, const std::string group_name) const
{
	PyRun_SimpleString(""
		"import redirect\n"
		"class CoutLogger:\n"
		"    def __init__(self):\n"
		"        self.buf = []\n"
		"    def write(self, data):\n"
		"        self.buf.append(data)\n"
		"        if data.endswith('\\n'):\n"
		"            redirect.sgems_cout(''.join(self.buf))\n"
		"            self.buf = []\n"
		"\n"
		"class CerrLogger:\n"
		"    def __init__(self):\n"
		"        self.buf = []\n"
		"    def write(self, data):\n"
		"        self.buf.append(data)\n"
		"        if data.endswith('\\n'):\n"
		"            redirect.sgems_cerr(''.join(self.buf))\n"
		"            self.buf = []\n"
		"\n"
		"import sys\n"
		"sys.stdout = CoutLogger()\n"
		"sys.stderr = CerrLogger()\n"
		"");

	FILE* fp = fopen(filename_.c_str(), "r");
	if (!fp)
	{
		GsTLcerr << "can't open file " << filename_ << gstlIO::end;
		return;
	}

	PyObject* module = PyImport_AddModule("__main__");
	PyObject* dictionary = PyModule_GetDict(module);
	PyObject* dictionary_copy = PyDict_Copy(dictionary);

	PyRun_File(fp, filename_.c_str(), Py_file_input, dictionary_copy, dictionary_copy);

	PyObject* function = PyDict_GetItemString(dictionary_copy, "sgems_execute_group_action");
	if (PyCallable_Check(function))
	{
		PyObject* result = PyObject_CallFunction(function, "ss", grid_name.c_str(), group_name.c_str());

		//		if (NULL == result)
		//		{
		//			std::cout << "execution failed\n";
		//		}

		Py_XDECREF(result);
	}

	Py_XDECREF(dictionary_copy);
	fclose(fp);
}
Exemplo n.º 15
0
void test() {

    print_line("testing python");
    PyRun_SimpleString("import engine\n");
    PyRun_SimpleString("def test(self):\n\tprint(\"noway\")\n");
    PyRun_SimpleString("a=engine.ObjectPtr()\n");
    PyRun_SimpleString("a.noway(22,'hello')\n");
    PyRun_SimpleString("a.normalize()\n");
    PyRun_SimpleString("class Moch(engine.ObjectPtr):\n\tdef mooch(self):\n\t\tprint('muchi')\n");
    PyRun_SimpleString("b=Moch();\n");
    PyRun_SimpleString("b.mooch();\n");
    PyRun_SimpleString("b.meis();\n");


}
Exemplo n.º 16
0
std::string TCP2::getMessage() {
	std::string s;
	PyRun_SimpleString("d = open('storage_tcp2.txt','w')\n"
		"d.write(s2.recv(1024))\n"
		"d.close()\n");
	std::ifstream infile;
	infile.open("storage_tcp2.txt");
	getline(infile, s);
	return s;
}
Exemplo n.º 17
0
//---------------------------------------------------------------------------------
// Adds a path to sys.path (relative to GetSourcePythonDir()).
//---------------------------------------------------------------------------------
void AddToSysPath( const char* path )
{
	char szFolderPath[MAX_PATH_LENGTH];
	V_snprintf(szFolderPath, MAX_PATH_LENGTH, "%s%s", GetSourcePythonDir(), path);
	V_FixSlashes(szFolderPath);

	DevMsg(1, MSG_PREFIX "Adding %s to path\n", szFolderPath);
	std::string szCommandString = "sys.path.append(r\"" + std::string(szFolderPath) + "\")";
	PyRun_SimpleString(szCommandString.c_str());
}
Exemplo n.º 18
0
//---------------------------------------------------------------------------------
// Adds a path to sys.path (relative to g_GamePaths.GetSPDir()).
//---------------------------------------------------------------------------------
void AddToSysPath( const char* path )
{
	char szFolderPath[MAX_GAME_PATH];
	V_snprintf(szFolderPath, MAX_GAME_PATH, "%s%s", g_GamePaths.GetSPDir(), path);
	V_FixSlashes(szFolderPath);

	DevMsg(1, "[SP] Adding %s to path\n", szFolderPath);
	std::string szCommandString = "sys.path.append(r\"" + std::string(szFolderPath) + "\")";
	PyRun_SimpleString(szCommandString.c_str());
}
Exemplo n.º 19
0
void vette_assertInitialized() {
   if( !Py_IsInitialized() ) {
      Py_Initialize();
   }
   if( !vette_IsLoaded ) {
      if( elDEBUG ) printf( "PYTHON CALL: import vette\n" );
      PyRun_SimpleString( (char*)"import vette" );
      vette_IsLoaded = 1;
   }
}
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); 

}
Exemplo n.º 21
0
bool Python::load()
{
    InputOutput::ScreenManager *S = InputOutput::ScreenManager::singleton();
    char msg[1024];
    PyObject *modName;

    char comm[512];
    strcpy(comm, "");
    PyRun_SimpleString("curdir = os.getcwd()");
    const char *path = getFolderFromFilePath((const char*)_script);
    const char *filename = getFileNameFromFilePath((const char*)_script);
    if(path[0]=='.')   // "./" prefix has been set
        sprintf(comm, "modulePath = curdir + \"%s\"", &path[1]);
    else
        sprintf(comm, "modulePath = \"%s\"", path);
    PyRun_SimpleString(comm);
    PyRun_SimpleString("sys.path.append(modulePath)");

    modName = PyUnicode_FromString(filename);
    _module = PyImport_Import(modName);
    Py_DECREF(modName); modName=0;
    if(!_module){
        sprintf(msg,
                "Python module \"%s\" cannot be imported.\n",
                filename);
        S->addMessageF(3, msg);
        printf("\n--- Python report --------------------------\n\n");
        PyErr_Print();
        printf("\n-------------------------- Python report ---\n");
        return true;
    }

    _func = PyObject_GetAttrString(_module, "main");
    if(!_func || !PyCallable_Check(_func)) {
        S->addMessageF(3, "main() function cannot be found.\n");
        printf("\n--- Python report --------------------------\n\n");
        PyErr_Print();
        printf("\n-------------------------- Python report ---\n");
        return true;
    }
    return false;
}
Exemplo n.º 22
0
	void PythonLanguage::runScriptPtr(const char* ptr) {
	    // Is this the right way?
        PyRun_SimpleString(ptr);

        if (PyErr_Occurred()) {
			// TODO: Do something useful here, or forget it
			// TODO: PythonException(BasicException) with the PyErr string probably. Same in the init
			PyErr_Print();
			PyErr_Clear();
		}
	}
Exemplo n.º 23
0
int main(int argc, char*argv[])
{
    Py_Initialize();

    PyRun_SimpleString("print 'Hello_World' ");
    Py_Finalize();

    puts("按任意键退出...");
    system("read -n 1");
    return   0 ;
}
Exemplo n.º 24
0
void VetteData_load_data(int arg0) {
   ElString __vetteRunString = elStrNew();
   vette_assertInitialized();
   elStrAppendString( __vetteRunString, "__vetteObj" );
   elStrAppendInt( __vetteRunString, arg0 );
   elStrAppendString( __vetteRunString, ".load_data( " );
   elStrAppendString( __vetteRunString, " )" );
   if( elDEBUG ) printf( "PYTHON CALL: %s\n", elStrGet( __vetteRunString ) );
   PyRun_SimpleString( elStrGet( __vetteRunString ) );
   elStrDestroy( __vetteRunString );
}
Exemplo n.º 25
0
void rabbit_init(RABBIT_MODE mode, void * instance) {
    if (mode == RABBIT_MODE_LUA) {
        lua_State * L = (lua_State *)instance;
        luaL_newlib(L, _rabbit_lib);
        lua_setglobal(L, "rabbit");
    }
    else {
        Py_InitModule("rabbit", _rabbit_defs);
        PyRun_SimpleString("import rabbit");
    }
}
Exemplo n.º 26
0
int main(int argc, char *argv[])
{


    Py_Initialize();

#ifdef _PYTHON_3X

    PyRun_SimpleString("from time import time,ctime\n"
                       "print('Today is', ctime(time()))\n");
#else
    PyRun_SimpleString("from time import time,ctime\n"
                       "print 'Today is', ctime(time())\n");

#endif

    Py_Finalize();

    return 0;
}
Exemplo n.º 27
0
PyObject *pytherl_eval(char *code, char *var_name, ErlNifMutex *mutex) {
    enif_mutex_lock(mutex);
    if(!Py_IsInitialized()) {
        Py_Initialize();
    }

    PyRun_SimpleString(code);
    enif_mutex_unlock(mutex);

    return pytherl_value(var_name, mutex);
};
Exemplo n.º 28
0
PyObject *pytherl_call(char *mod, char *fun, char *args, int arg_size, ErlNifMutex *mutex) {
  char *command = (char *)calloc(2*(arg_size + strlen(fun)), sizeof(char));
  assert(command);

  enif_mutex_lock(mutex);
  if(!Py_IsInitialized()) {
    Py_Initialize();
  }

  sprintf(command, "import %s", mod);
  PyRun_SimpleString(command);

  sprintf(command, "__pytherl_result = %s(%s)", fun, args);
  PyRun_SimpleString(command);
  enif_mutex_unlock(mutex);

  free(command);

  return pytherl_result(mutex);
};
Exemplo n.º 29
0
PyInterpreter::PyInterpreter()
    : pycompleter(0), pycomplete(0)
{
#if PY_MAJOR_VERSION >= 3
    PyImport_AppendInittab("pypangolin", InitPyPangolinModule);
    Py_Initialize();
#else
    Py_Initialize();
    InitPyPangolinModule();
#endif

    // Hook stdout, stderr to this interpreter
    PyObject* mod_sys = PyImport_ImportModule("sys");
    if (mod_sys) {
        PyModule_AddObject(mod_sys, "stdout", (PyObject*)new PyPangoIO(
            &PyPangoIO::Py_type, line_queue, ConsoleLineTypeStdout
            ));
        PyModule_AddObject(mod_sys, "stderr", (PyObject*)new PyPangoIO(
            &PyPangoIO::Py_type, line_queue, ConsoleLineTypeStderr
            ));
    } else {
        pango_print_error("Couldn't import module sys.\n");
    }

    // Attempt to setup readline completion
    PyRun_SimpleString(
        "import pypangolin\n"
        "try:\n"
        "   import readline\n"
        "except ImportError:\n"
        "   import pyreadline as readline\n"
        "\n"
        "import rlcompleter\n"
        "pypangolin.completer = rlcompleter.Completer()\n"
    );
    CheckPrintClearError();

    // Get reference to rlcompleter.Completer() for tab-completion
    PyObject* mod_pangolin = PyImport_ImportModule("pypangolin");
    if(mod_pangolin) {
        pycompleter = PyObject_GetAttrString(mod_pangolin,"completer");
        if(pycompleter) {
            pycomplete  = PyObject_GetAttrString(pycompleter,"complete");
        }
    } else {
        pango_print_error("PyInterpreter: Unable to load module pangolin.\n");
    }

    // Hook namespace prefixes into Python
    RegisterNewVarCallback(&PyInterpreter::AttachPrefix, (void*)this, "");
    ProcessHistoricCallbacks(&PyInterpreter::AttachPrefix, (void*)this, "");

    CheckPrintClearError();
}
Exemplo n.º 30
0
int runPython(const char* path, int argc, char* argv[])
{
    Py_Initialize();
    PyRun_SimpleString(getInit().c_str());
    FILE* fp = fopen(path, "r");
    PyRun_SimpleFile(fp, path);
    fclose(fp);
    Py_Finalize();

    return 0;
}