Ejemplo n.º 1
0
//Desctructor
QPyConsole::~QPyConsole()
{
    Py_Finalize();
}
Ejemplo n.º 2
0
//! Finalizes Python VM
void
script_finalize()
{
    Py_Finalize();
}
void PyEmbedder::FinalizePython()
{
	if(Py_IsInitialized())
		Py_Finalize();
}
Ejemplo n.º 4
0
int
main(int argc, char *argv[])
{
    PyObject *pName, *pModule, *pDict, *pFunc;
    PyObject *pArgs, *pValue;
    int i;

    if (argc < 3) {
        fprintf(stderr,"Usage: call pythonfile funcname [args]\n");
        return 1;
    }

    Py_Initialize();
    pName = PyString_FromString(argv[1]);
    /* Error checking of pName left out */

    pModule = PyImport_Import(pName);
    Py_DECREF(pName);

    if (pModule != NULL) {
        pFunc = PyDict_GetAttrString(pModule, argv[2]);
        /* pFunc is a new reference */

        if (pFunc && PyCallable_Check(pFunc)) {
            pArgs = PyTuple_New(argc - 3);
            for (i = 0; i < argc - 3; ++i) {
                pValue = PyInt_FromLong(atoi(argv[i + 3]));
                if (!pValue) {
                    Py_DECREF(pArgs);
                    Py_DECREF(pModule);
                    fprintf(stderr, "Cannot convert argument\n");
                    return 1;
                }
                /* pValue reference stolen here: */
                PyTuple_SetItem(pArgs, i, pValue);
            }
            pValue = PyObject_CallObject(pFunc, pArgs);
            Py_DECREF(pArgs);
            if (pValue != NULL) {
                printf("Result of call: %ld\n", PyInt_AsLong(pValue));
                Py_DECREF(pValue);
            }
            else {
                Py_DECREF(pFunc);
                Py_DECREF(pModule);
                PyErr_Print();
                fprintf(stderr,"Call failed\n");
                return 1;
            }
        }
        else {
            if (PyErr_Occurred())
                PyErr_Print();
            fprintf(stderr, "Cannot find function \"%s\"\n", argv[2]);
        }
        Py_XDECREF(pFunc);
        Py_DECREF(pModule);
    }
    else {
        PyErr_Print();
        fprintf(stderr, "Failed to load \"%s\"\n", argv[1]);
        return 1;
    }
    Py_Finalize();
    return 0;
}
Ejemplo n.º 5
0
PythonTools::~PythonTools()
{
    Py_Finalize();
}
Ejemplo n.º 6
0
/*....................................................................*/
int
main(int argc, char *argv[]){
  errType err=init_local_err();
  PyObject *pCurrentModel,*pLimePars,*pModule;
  const int maxLenName=100;
  char userModuleNameNoSuffix[maxLenName+1];
  int modelI=-1,nPars,nImgPars,nImages,status=0;
  char message[STR_LEN_1];
  const char *headerModuleName="limepar_classes";
  inputPars par;
  image *img = NULL;
  parTemplateType *parTemplates=NULL,*imgParTemplates=NULL;

  if (argc < 2){
    printf("Usage: casalime <name of file with pickled pars object>\n");
exit(1);
  }

  /* . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
  Py_Initialize();

  /* pCurrentModel should be a modellib_classes._Model instance, pLimePars should be a limepar_classes.ModelParameters instance. */
  _readParsObjWrapper(argv[1], &pCurrentModel, userModuleNameNoSuffix, maxLenName, &copyTemp, &pLimePars);

  /* Do some initialization */
  setDefaultFuncStuffs(); /* in ml_funcs */
  silent = 0;//********** pass it as argument?
  defaultFuncFlags = 0;

  if(pCurrentModel==Py_None){
    currentModelI = MODEL_None;
  }else{
    err = getModelI(pCurrentModel, &modelI); /* in ml_aux.c */
    if(err.status!=0){
      Py_DECREF(pCurrentModel);
      Py_DECREF(pLimePars);
pyerror(err.message);
    }

    currentModelI = modelI; /* global var. */

    /* Set some global arrays defined in the header of ml_models.c */
    err = extractParams(pCurrentModel); /* in ml_aux.c */
    if(err.status!=0){
      Py_DECREF(pCurrentModel);
      Py_DECREF(pLimePars);
pyerror(err.message);
    }

    /* Set some global arrays defined in the header of ml_funcs.c */
    err = extractFuncs(pCurrentModel); /* in ml_aux.c */
    if(err.status!=0){
      Py_DECREF(pCurrentModel);
      Py_DECREF(pLimePars);
pyerror(err.message);
    }
  }

  Py_DECREF(pCurrentModel);

  status = finalizeModelConfig(currentModelI); /* in ml_models.c */
  if(status!=0){
    Py_DECREF(pLimePars);
    sprintf(message, "finalizeModelConfig() returned status value %d", status);
pyerror(message);
  }

  /* . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
  /* Construct the 'macro' list argument:
  */
  err = setMacros(); /* in py_utils.c */
  if(err.status){
    Py_DECREF(pLimePars);
    unsetMacros(); /* in py_utils.c */
pyerror(err.message);
  }

  /* Set up any user-supplied result functions: */
  if(strlen(userModuleNameNoSuffix)>0){
    err = getModuleFromName(userModuleNameNoSuffix, &pModule); /* in py_utils.c */
    if(err.status!=0){ /* Don't need to decref pModule. */
      Py_DECREF(pLimePars);
pyerror(err.message);
    }

    /* Sets up global objects defined in the header of py_utils.c */
    setUpUserPythonFuncs(pModule); /* in py_utils.c */

    Py_DECREF(pModule);
  }

  /* Now get the lists of attribute names from the 2 classes in limepar_classes.py:
  */
  err = getParTemplatesWrapper(headerModuleName, &parTemplates, &nPars\
    , &imgParTemplates, &nImgPars); /* in py_utils.c */
  if(err.status!=0){
    Py_DECREF(pLimePars);
pyerror(err.message);
  }

  err = mallocInputParStrs(&par);
  if(err.status){
    unsetMacros();
    Py_DECREF(pLimePars);
pyerror(err.message);
  }

  /* Finally, unpack the LIME parameter values, following the templates: */
  err = readParImg(pLimePars, parTemplates, nPars, imgParTemplates\
    , nImgPars, &par, &img, &nImages, pywarning); /* in py_utils.c */

  if(err.status){
    Py_DECREF(pLimePars);
pyerror(err.message);
  }

  Py_DECREF(pLimePars);
  free(imgParTemplates);
  free(parTemplates);

  /* . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
  /* Now call the main bit of LIME:
  */
  status = run(par, img, nImages);

  /* Python-object clean up before status check and possible exit.
  */
  decrefAllUserFuncs(); /* in py_utils.c */
  free(modelDblPars); /* global in header of ml_models.c */
  free(modelIntPars); /* global in header of ml_models.c */
//************* why not the str pars??
  freeFuncsPars(); /* in ml_funcs.c */

  if(status){
    sprintf(message, "Function run() returned with status %d", status);
pyerror(message);
  }

  Py_Finalize();

  return 0;
}
Ejemplo n.º 7
0
void OllyPython_Destroy(void)
{
    Py_Finalize();

    initialized = 0;
}
Ejemplo n.º 8
0
/* int main(int argc, char **argv) { */
int main(int argc, char *argv[]) {

    char *env_argument = NULL;
    int ret = 0;
    FILE *fd;

 /* AND: Several filepaths are hardcoded here, these must be made
    configurable */
 /* AND: P4A uses env vars...not sure what's best */
    LOG("Initialize Python for Android");
    /* env_argument = "/data/data/org.kivy.android/files"; */
    env_argument = getenv("ANDROID_ARGUMENT");
    setenv("ANDROID_APP_PATH", env_argument, 1);
    
    /* setenv("ANDROID_ARGUMENT", env_argument, 1); */
    /* setenv("ANDROID_PRIVATE", env_argument, 1); */
    /* setenv("ANDROID_APP_PATH", env_argument, 1); */
    /* setenv("PYTHONHOME", env_argument, 1); */
    /* setenv("PYTHONPATH", "/data/data/org.kivy.android/files:/data/data/org.kivy.android/files/lib", 1); */

    /* LOG("AND: Set env vars"); */
    /* LOG(argv[0]); */
    /* LOG("AND: That was argv 0"); */
	//setenv("PYTHONVERBOSE", "2", 1);
    
    LOG("Changing directory to the one provided by ANDROID_ARGUMENT");
    LOG(env_argument);
    chdir(env_argument);

    Py_SetProgramName(L"android_python");

#if PY_MAJOR_VERSION >= 3
    /* our logging module for android
     */
    PyImport_AppendInittab("androidembed", initandroidembed);
#endif
    
    LOG("Preparing to initialize python");
    
    if (dir_exists("crystax_python/")) {
      LOG("crystax_python exists");
        char paths[256];
        snprintf(paths, 256, "%s/crystax_python/stdlib.zip:%s/crystax_python/modules", env_argument, env_argument);
        /* snprintf(paths, 256, "%s/stdlib.zip:%s/modules", env_argument, env_argument); */
        LOG("calculated paths to be...");
        LOG(paths);
        
#if PY_MAJOR_VERSION >= 3
        wchar_t* wchar_paths = Py_DecodeLocale(paths, NULL);
        Py_SetPath(wchar_paths);
#else
        char* wchar_paths = paths;
        LOG("Can't Py_SetPath in python2, so crystax python2 doesn't work yet");
        exit(1);
#endif
     
        LOG("set wchar paths...");
    } else { LOG("crystax_python does not exist");}

    Py_Initialize();
    
#if PY_MAJOR_VERSION < 3
    PySys_SetArgv(argc, argv);
#endif
    
    LOG("Initialized python");

    /* ensure threads will work.
     */
    LOG("AND: Init threads");
    PyEval_InitThreads();
    

#if PY_MAJOR_VERSION < 3
    initandroidembed();
#endif

    PyRun_SimpleString("import androidembed\nandroidembed.log('testing python print redirection')");
    
    /* inject our bootstrap code to redirect python stdin/stdout
     * replace sys.path with our path
     */
    PyRun_SimpleString("import sys, posix\n");
    if (dir_exists("lib")) {
        /* If we built our own python, set up the paths correctly */
      LOG("Setting up python from ANDROID_PRIVATE");
        PyRun_SimpleString(
            "private = posix.environ['ANDROID_PRIVATE']\n" \
            "argument = posix.environ['ANDROID_ARGUMENT']\n" \
            "sys.path[:] = [ \n" \
            "    private + '/lib/python27.zip', \n" \
            "    private + '/lib/python2.7/', \n" \
            "    private + '/lib/python2.7/lib-dynload/', \n" \
            "    private + '/lib/python2.7/site-packages/', \n" \
            "    argument ]\n");
    } 

    if (dir_exists("crystax_python")) {
      char add_site_packages_dir[256];
      snprintf(add_site_packages_dir, 256, "sys.path.append('%s/crystax_python/site-packages')", 
               env_argument);
      
      PyRun_SimpleString(
          "import sys\n"             \
          "sys.argv = ['notaninterpreterreally']\n"  \
          "from os.path import realpath, join, dirname");
      PyRun_SimpleString(add_site_packages_dir);
      /* "sys.path.append(join(dirname(realpath(__file__)), 'site-packages'))") */
      PyRun_SimpleString("sys.path = ['.'] + sys.path");
    }
    
    PyRun_SimpleString(
        "class LogFile(object):\n" \
        "    def __init__(self):\n" \
        "        self.buffer = ''\n" \
        "    def write(self, s):\n" \
        "        s = self.buffer + s\n" \
        "        lines = s.split(\"\\n\")\n" \
        "        for l in lines[:-1]:\n" \
        "            androidembed.log(l)\n" \
        "        self.buffer = lines[-1]\n" \
        "    def flush(self):\n" \
        "        return\n" \
        "sys.stdout = sys.stderr = LogFile()\n" \
		"print('Android path', sys.path)\n" \
        "import os\n" \
        "print('os.environ is', os.environ)\n" \
        "print('Android kivy bootstrap done. __name__ is', __name__)");

#if PY_MAJOR_VERSION < 3
    PyRun_SimpleString("import site; print site.getsitepackages()\n");
#endif

    /* PyRun_SimpleString( */
    /*     "import sys, posix\n" \ */
    /*     "private = posix.environ['ANDROID_PRIVATE']\n" \ */
    /*     "argument = posix.environ['ANDROID_ARGUMENT']\n" \ */
    /*     "sys.path[:] = [ \n" \ */
	/* 	"    private + '/lib/python27.zip', \n" \ */
	/* 	"    private + '/lib/python2.7/', \n" \ */
	/* 	"    private + '/lib/python2.7/lib-dynload/', \n" \ */
	/* 	"    private + '/lib/python2.7/site-packages/', \n" \ */
	/* 	"    argument ]\n" \ */
    /*     "import androidembed\n" \ */
    /*     "class LogFile(object):\n" \ */
    /*     "    def __init__(self):\n" \ */
    /*     "        self.buffer = ''\n" \ */
    /*     "    def write(self, s):\n" \ */
    /*     "        s = self.buffer + s\n" \ */
    /*     "        lines = s.split(\"\\n\")\n" \ */
    /*     "        for l in lines[:-1]:\n" \ */
    /*     "            androidembed.log(l)\n" \ */
    /*     "        self.buffer = lines[-1]\n" \ */
    /*     "    def flush(self):\n" \ */
    /*     "        return\n" \ */
    /*     "sys.stdout = sys.stderr = LogFile()\n" \ */
	/* 	"import site; print site.getsitepackages()\n"\ */
	/* 	"print 'Android path', sys.path\n" \ */
    /*     "print 'Android kivy bootstrap done. __name__ is', __name__"); */

    LOG("AND: Ran string");

    /* run it !
     */
    LOG("Run user program, change dir and execute main.py");

	/* search the initial main.py
	 */
	char *main_py = "main.pyo";
	if ( file_exists(main_py) == 0 ) {
		if ( file_exists("main.py") )
			main_py = "main.py";
		else
			main_py = NULL;
	}

	if ( main_py == NULL ) {
		LOG("No main.pyo / main.py found.");
		return -1;
	}

    fd = fopen(main_py, "r");
    if ( fd == NULL ) {
        LOG("Open the main.py(o) failed");
        return -1;
    }

    /* run python !
     */
    ret = PyRun_SimpleFile(fd, main_py);

    if (PyErr_Occurred() != NULL) {
        ret = 1;
        PyErr_Print(); /* This exits with the right code if SystemExit. */
        PyObject *f = PySys_GetObject("stdout");
        if (PyFile_WriteString("\n", f))  /* python2 used Py_FlushLine, but this no longer exists */
          PyErr_Clear();
    }

    /* close everything
     */
	Py_Finalize();
    fclose(fd);

    LOG("Python for android ended.");
    return ret;
}
Ejemplo n.º 9
0
void finalize_scripts(void) {
  Py_Finalize();
}
Ejemplo n.º 10
0
int main(int argc, char *argv[])
{
   Py_InitializeEx(0);
   uint32_t env_flags = af::Environment::AppendPythonPath;
#ifdef WINNT
   env_flags = env_flags | af::Environment::Verbose; // Verbose environment initialization
#else
//
// interrupt signal catch:
   struct sigaction actint;
   bzero( &actint, sizeof(actint));
   actint.sa_handler = sig_int;
   sigaction( SIGINT,  &actint, NULL);
   sigaction( SIGTERM, &actint, NULL);
   sigaction( SIGSEGV, &actint, NULL);
// SIGPIPE signal catch:
   struct sigaction actpipe;
   bzero( &actpipe, sizeof(actpipe));
   actpipe.sa_handler = sig_pipe;
   sigaction( SIGPIPE, &actpipe, NULL);
#endif
   af::Environment ENV( env_flags, argc, argv);  // Silent environment initialization

   if( !ENV.isValid())
   {
      AFERROR("main: Environment initialization failed.")
      exit(1);
   }

   afqt::init( ENV.getWatchWaitForConnected(), ENV.getWatchWaitForReadyRead(), ENV.getWatchWaitForBytesWritten());
   afqt::QEnvironment QENV( "watch");
   if( !QENV.isValid())
   {
      AFERROR("main: QEnvironment initialization failed.")
      exit(1);
   }

   QApplication app(argc, argv);
   app.setWindowIcon( QIcon( afqt::stoq( ENV.getCGRULocation()) + "/icons/afwatch.png"));
	app.setStyle("plastique");

	MonitorHost monitor;

   Dialog dialog;
   if( !dialog.isInitialized())
   {
      AFERROR("main: Dialog initialization failed.")
      exit(1);
   }

   Watch watch( &dialog, &app);

   dialog.show();
   QObject::connect( &dialog, SIGNAL( stop()), &app, SLOT( quit()));

   int status = app.exec();

   af::destroy();
   Py_Finalize();

   AFINFA("main: QApplication::exec: returned status = %d", status)

   return status;
}
Ejemplo n.º 11
0
bool obs_module_load()
{
    blog(LOG_INFO, "obs_module_load");

    if(!is_python_on_path()){
      blog(LOG_WARNING,
	   "%s:l%i \"Warning could not detect python environment variables attempting to load shared library anyway\"",
	   __func__,
	   __LINE__
	   );      
    }

    // Manually force python to be loaded
#if __GNUC__
    if(!os_dlopen_global(PYTHON_SHARED_LIBRARY_NAME)){
#else
      if(!os_dlopen(PYTHON_SHARED_LIBRARY_NAME)){
#endif
	blog(LOG_ERROR,
	    "%s:l%i \"Error Could not load python shared library %s aborting!\"",
	    __func__,
	    __LINE__,
	    PYTHON_SHARED_LIBRARY_NAME
	    );      
	return false;
    }


    Py_Initialize();
    PyEval_InitThreads();
 

    /*Must set arguments for guis to work*/
    wchar_t* argv[] = { L"", NULL };
    int argc = sizeof(argv) / sizeof(wchar_t*) - 1;
  

    PySys_SetArgv(argc, argv);

    /* Setup logs to a safe place can be changed by user in OBSPythonManager.py register function*/
    PyRun_SimpleString("import os");
    PyRun_SimpleString("import sys");
    PyRun_SimpleString("os.environ['PYTHONUNBUFFERED'] = '1'");
    /* TODO  change to non platform specific */
    PyRun_SimpleString("sys.stdout = open('./stdOut.txt','w',1)");
    PyRun_SimpleString("sys.stderr = open('./stdErr.txt','w',1)");
    PyRun_SimpleString("print(sys.version)");

    
    /*Load manager from file*/    
    PyObject* pName = NULL;
    PyObject* pModule = NULL;
    PyObject* pFunc = NULL;
    PyObject* argList = NULL;

    bool ret = false;

    char script[] = "/scripts";
    char arch[] = PLUGINARCH;
    const char *data_path = obs_get_module_data_path(obs_current_module());
    char *scripts_path = bzalloc(strlen(data_path)+strlen(script));
    
    strcpy(scripts_path,data_path);
    strcat(scripts_path,script);


    //Add the scripts path to env
    add_to_python_path(scripts_path);

    bfree(scripts_path);
    

    scripts_path = bzalloc(strlen(data_path)+strlen(arch));
    strcpy(scripts_path,data_path);
    strcat(scripts_path,arch);

    //Add the plugin obspython arch path to env
    add_to_python_path(scripts_path);


    /* load the obspython library and extend with manually written functions/objects  */
    PyObject *py_libobs = PyImport_ImportModule("obspython");
    ret = pyHasError();
    if (ret){
      blog(LOG_INFO,
	   "%s:l%i \"Error importing '%s/obspython.py' unloading obs-python\"",
	   __func__,
	   __LINE__,
	   scripts_path
	   );
      goto out;
    }

    extend_swig_libobs(py_libobs);


    //Import the manager script
    pName = PyUnicode_FromString("OBSPythonManager");
    pModule = PyImport_Import(pName);

    ret = pyHasError();
    if (ret){
      blog(LOG_INFO,
	     "%s:l%i \"Error loading '%s/OBSPythonManager.py' unloading obs-python\"",
	     __func__,
	     __LINE__,
	     scripts_path
	     );
      goto out;
    }
    
    //get the function by name
    if(pModule != NULL) {
      PyModule_AddObject(pModule,"obspython",py_libobs);
      pFunc = PyObject_GetAttr(pModule, PyUnicode_FromString("obs_module_load"));
        if(pFunc != NULL) {
	  argList = Py_BuildValue("()");
            PyObject_CallObject(pFunc,argList);
	    ret = pyHasError();
	    if (ret){
	      blog(LOG_INFO,
		   "%s:l%i \"Error running 'register' function in '%s/OBSPythonManager.py' unloading obs-python\"",
		   __func__,
		   __LINE__,
		   scripts_path
		   );
	      goto out;
	    }
	}else{
	  ret = pyHasError();
	  blog(LOG_INFO,
	       "%s:l%i \"Could not find register function in '%s/OBSPythonManager.py' unloading obs-python\"",
	       __func__,
	       __LINE__,
	       scripts_path
	       );
	}
	goto out;
    }

 out:
    bfree(scripts_path);    
    Py_XDECREF(pFunc);
    Py_XDECREF(argList);
    Py_XDECREF(pModule);
    Py_XDECREF(pName); 
    //Release the thread GIL
    PyThreadState* pts = PyGILState_GetThisThreadState();
    PyEval_ReleaseThread(pts);
    if(!ret){    
       return true;
    }else{    
        obs_module_unload();
        return false;
    }
}

void obs_module_unload()
{
    //Shutdown python and call shutdown functions
    blog(LOG_INFO, "obs_module_unload");

    PyGILState_STATE gstate;
    gstate = PyGILState_Ensure();

    UNUSED_PARAMETER(gstate);

    if (Py_IsInitialized()) {
        Py_Finalize();
    }

}
Ejemplo n.º 12
0
WebsiteAuto::~WebsiteAuto()
{
	Py_Finalize();

	std::cout << "Browser successfully running." << std::endl;
}
Ejemplo n.º 13
0
static int test_init_from_config(void)
{
    /* Test _Py_InitializeFromConfig() */
    _PyCoreConfig config = _PyCoreConfig_INIT;
    config.install_signal_handlers = 0;

    /* FIXME: test use_environment */

    putenv("PYTHONHASHSEED=42");
    config.use_hash_seed = 1;
    config.hash_seed = 123;

    putenv("PYTHONMALLOC=malloc");
    config.allocator = "malloc_debug";

    /* dev_mode=1 is tested in test_init_dev_mode() */

    putenv("PYTHONFAULTHANDLER=");
    config.faulthandler = 1;

    putenv("PYTHONTRACEMALLOC=0");
    config.tracemalloc = 2;

    putenv("PYTHONPROFILEIMPORTTIME=0");
    config.import_time = 1;

    config.show_ref_count = 1;
    config.show_alloc_count = 1;
    /* FIXME: test dump_refs: bpo-34223 */

    putenv("PYTHONMALLOCSTATS=0");
    config.malloc_stats = 1;

    /* FIXME: test coerce_c_locale and coerce_c_locale_warn */

    putenv("PYTHONUTF8=0");
    Py_UTF8Mode = 0;
    config.utf8_mode = 1;

    putenv("PYTHONPYCACHEPREFIX=env_pycache_prefix");
    config.pycache_prefix = L"conf_pycache_prefix";

    Py_SetProgramName(L"./globalvar");
    config.program_name = L"./conf_program_name";

    static wchar_t* argv[2] = {
        L"-c",
        L"pass",
    };
    config.argc = Py_ARRAY_LENGTH(argv);
    config.argv = argv;

    config.program = L"conf_program";

    static wchar_t* xoptions[3] = {
        L"core_xoption1=3",
        L"core_xoption2=",
        L"core_xoption3",
    };
    config.nxoption = Py_ARRAY_LENGTH(xoptions);
    config.xoptions = xoptions;

    static wchar_t* warnoptions[2] = {
        L"default",
        L"error::ResourceWarning",
    };
    config.nwarnoption = Py_ARRAY_LENGTH(warnoptions);
    config.warnoptions = warnoptions;

    /* FIXME: test module_search_path_env */
    /* FIXME: test home */
    /* FIXME: test path config: module_search_path .. dll_path */

    putenv("PYTHONVERBOSE=0");
    Py_VerboseFlag = 0;
    config.verbose = 1;

    Py_NoSiteFlag = 0;
    config.site_import = 0;

    Py_BytesWarningFlag = 0;
    config.bytes_warning = 1;

    putenv("PYTHONINSPECT=");
    Py_InspectFlag = 0;
    config.inspect = 1;

    Py_InteractiveFlag = 0;
    config.interactive = 1;

    putenv("PYTHONOPTIMIZE=0");
    Py_OptimizeFlag = 1;
    config.optimization_level = 2;

    /* FIXME: test parser_debug */

    putenv("PYTHONDONTWRITEBYTECODE=");
    Py_DontWriteBytecodeFlag = 0;
    config.write_bytecode = 0;

    Py_QuietFlag = 0;
    config.quiet = 1;

    putenv("PYTHONUNBUFFERED=");
    Py_UnbufferedStdioFlag = 0;
    config.buffered_stdio = 0;

    putenv("PYTHONIOENCODING=cp424");
    Py_SetStandardStreamEncoding("ascii", "ignore");
#ifdef MS_WINDOWS
    /* Py_SetStandardStreamEncoding() sets Py_LegacyWindowsStdioFlag to 1.
       Force it to 0 through the config. */
    config.legacy_windows_stdio = 0;
#endif
    config.stdio_encoding = "iso8859-1";
    config.stdio_errors = "replace";

    putenv("PYTHONNOUSERSITE=");
    Py_NoUserSiteDirectory = 0;
    config.user_site_directory = 0;

    config._check_hash_pycs_mode = "always";

    Py_FrozenFlag = 0;
    config._frozen = 1;

    _PyInitError err = _Py_InitializeFromConfig(&config);
    /* Don't call _PyCoreConfig_Clear() since all strings are static */
    if (_Py_INIT_FAILED(err)) {
        _Py_FatalInitError(err);
    }
    dump_config();
    Py_Finalize();
    return 0;
}
Ejemplo n.º 14
0
void ThreadProc( void *data )
{
    PyObject *pName, *pModule, *pDict, *pFunc;
    PyThreadState *mainThreadState, *myThreadState, *tempState;
    PyInterpreterState *mainInterpreterState;
    
    CMD_LINE_STRUCT* arg = (CMD_LINE_STRUCT*)data;

    // Initialize python inerpreter
    Py_Initialize();
        
    // Initialize thread support
    PyEval_InitThreads();

    // Save a pointer to the main PyThreadState object
    mainThreadState = PyThreadState_Get();

    // Get a reference to the PyInterpreterState
    mainInterpreterState = mainThreadState->interp;

    // Create a thread state object for this thread
    myThreadState = PyThreadState_New(mainInterpreterState);

	// Release global lock
	PyEval_ReleaseLock();
    
	// Acquire global lock
	PyEval_AcquireLock();

    // Swap in my thread state
    tempState = PyThreadState_Swap(myThreadState);

    // Now execute some python code (call python functions)
    pName = PyString_FromString(arg->argv[1]);
    pModule = PyImport_Import(pName);

    // pDict and pFunc are borrowed references 
    pDict = PyModule_GetDict(pModule);
    pFunc = PyDict_GetItemString(pDict, arg->argv[2]);

    if (PyCallable_Check(pFunc)) 
    {
        PyObject_CallObject(pFunc, NULL);
    }
    else {
        PyErr_Print();
    }

    // Clean up
    Py_DECREF(pModule);
    Py_DECREF(pName);

    // Swap out the current thread
    PyThreadState_Swap(tempState);

	// Release global lock
	PyEval_ReleaseLock();

    // Clean up thread state
    PyThreadState_Clear(myThreadState);
    PyThreadState_Delete(myThreadState);

    Py_Finalize();
    printf("My thread is finishing...\n");

    // Exiting the thread
#ifdef WIN32
    // Windows code
    _endthread();
#else
    // POSIX code
    pthread_exit(NULL);
#endif
}
Ejemplo n.º 15
0
int *CA_LoadCells(char *pattern, int width) {
    PyObject *pModuleName;  // the name of the module 
    PyObject *pModule;      // the module object
    PyObject *pFunc;        // the callable object 
    PyObject *pWidth;       // the width parameter of the CA
    PyObject *pArgs;        // the argument list to the callable
    PyObject *pResult;      // the result of the python invocation

    char *module_name = "capattern";
    int i;

    // initialize the python interpreter
    Py_Initialize();

    // add current directory to sys.path, so that import can succeed
    // alternative approach is to export: PYTHONPATH=. when starting the executable
    // NOTE: this is somehow wrong as it replaces sys.path
    //PySys_SetPath(".");

    // import the module
    pModuleName = PyString_FromString(module_name);
    pModule = PyImport_Import(pModuleName);

    if (pModule == NULL) {
        fprintf(stderr, "error: could not import module: %s\n", module_name);
        if (PyErr_Occurred()) {
            PyErr_Print();
        }
        return NULL;
    }
    
    // get a reference to the callable with the specified name
    pFunc = PyObject_GetAttrString(pModule, pattern);
    if (pFunc == NULL) {
        fprintf(stderr, "error: could not find callable: %s\n", pattern);
        return NULL;
    }

    if (!PyCallable_Check(pFunc)) {
        fprintf(stderr, "error: %s is not callable\n", pattern);
        return NULL;
    }

    // prepare the arguments for the callable
    pWidth = PyInt_FromLong(width);
    pArgs = PyTuple_New(1);
    PyTuple_SetItem(pArgs, 0, pWidth);

    // invoke the callable with the arguments
    pResult = PyObject_CallObject(pFunc, pArgs);

    // check for errors
    if (PyErr_Occurred()) {
        PyErr_Print();
        return NULL;
    }

    // check whether the result is a sequence
    if (!PySequence_Check(pResult)) {
        fprintf(stderr, "error: result is not a sequence\n");
        return NULL;
    }

    // check length of returned result
    if (PySequence_Size(pResult) != width) {
       fprintf(stderr, "error: returned sequence has incorrect length\n");
    }

    // allocate cells
    int *cells = (int *) malloc(width * sizeof(int));

    // iterate over elements in sequence
    for (i=0; i<width; i++) {
        // check that the element is an integer
        PyObject *pElement;
        pElement = PySequence_GetItem(pResult, i);
        if (!PyInt_Check(pElement)) {
            fprintf(stderr, "error: element with index %d is not an integer\n", i);
            return NULL;
        }

        // check that the element is equal to one or zero
        int value = PyInt_AsLong(pElement);
        if (!((value == 0) || (value == 1))) {
            fprintf(stderr, "error: element with index %d is not 0 or 1\n", i);
            return NULL;
        }

        // get the cell
        *(cells+i) = value;
    }

    Py_Finalize();
    return cells;
}
Ejemplo n.º 16
0
 ~CEngine(void)
 {
 	// Exit, cleaning up the interpreter
     Py_Finalize();
 }
Ejemplo n.º 17
0
int WINAPI WinMain(	HINSTANCE	hInstance,HINSTANCE	hPrevInstance,				
			LPSTR lpCmdLine,int	nCmdShow)				
{
	//In debug mode all logging is enabled by default.
	// Otherwise, additional logging must be enabled through the console.
	Log_Index.SetisEnabled(true);
	AppLog.SetisEnabled(true);
	ErrorLog.SetisEnabled(true);
#ifdef DEBUG
	
	InputLog_Gamepads.SetisEnabled(true);
	InputLog_Mouse.SetisEnabled(true);
	InputLog_Keyboard.SetisEnabled(true);
	ObjectsLog.SetisEnabled(true);
	ScenesLog.SetisEnabled(true);
	ResourceLog.SetisEnabled(true);
	//-----------------------------
	AppLog.WriteMessage("Running in DEBUG mode: ALL Logging Enabled by default.");
#endif

	AppLog.WriteMessage("The Application Entered the running state");
	srand ( time(NULL)^2);                  //Seed rand once for the entire application.
	MSG	msg;								    // Windows Message Structure
	bool done = false;						// Bool Variable To Exit Loop


    /////////////////////////////////////////////////////////////////////////
	//Sound Initalization
	MainAudio.InitOpenAL();
	//3d fixed point listening 
	MainAudio.SetListenerPos(0.0,0.0,-1.0); 
	MainAudio.SetListenerOrien(0.0, 0.0,-1.0,0.0,1.0, 0.0);
	MainAudio.SetListenerVel(0.0,0.0,0.0);
	AppLog.WriteMessage("OpenAL Initialized Successfully");

	//Initialize DirectInput & XInput

	Gamepads.InitDirectInput();
	AppLog.WriteMessage("DirectInput Initallized Successfully");
   

	//Initialize Python

	Py_Initialize();

	char ** argv;
	argv = new char *;
	PySys_SetArgv(0,argv);

	AppLog.WriteMessage("Python Initialized Successfully");

	
    ////////////////////////////////////////////////////////////////////////
	//Window Initialization


	//Quick 

#ifdef DEBUG   
	// Create Our OpenGL Window
	if(!TrogWin.GetActive())
	{
		if (!TrogWin.CreateGLWindow("Fleet",640,480,32,0))
		{
			AppLog.WriteMessage("In Debug Mode : Windowed failed to be created.");
			return 0;							// Quit If Window Was Not Created
		}

		TrogWin.SetActive(true);
		AppLog.WriteMessage("In Debug Mode : Window has been created.");
		AppLog.WriteMessage("OpenGL successfully initialized.");
	}


	/*!******************************************************
	* The section below does not work in Debug Mode        *
	********************************************************/


#else // Otherwise Load Settings from Config.ini
	
	// Create Our OpenGL Window
	if(!TrogWin.GetActive())
	{
			if(SM.Load_V_Settings()!=0)  //Load Video Initalization settings from config.ini
			{
				//if the config file could not be found, initialize with defualt settings

				if (!TrogWin.CreateGLWindow("Troglodyte Version 0.7.5 ",800,600,32,false))
				{
					return 0;							// Quit If Window Was Not Created
				}
				else
				{
					AppLog.WriteMessage("Config.ini could not be loaded. Default Window Created.");
				}
			}

				
			//Convert SM.V_Settings.AppName from a string to a const char * for window display

			const char * WindowText=NULL;

			WindowText = SM.V_Settings.AppName.c_str();

			
		   if (!TrogWin.CreateGLWindow((char *)WindowText,SM.V_Settings.width,SM.V_Settings.height,
					SM.V_Settings.CBits,SM.V_Settings.fullscreen))
				{
					MessageBox(NULL,"The Application could not be initialized!",
						"Applicaton Creation Error!",MB_ICONEXCLAMATION|MB_OK);
					return 0;							// Quit If Window Was Not Created
				}

				TrogWin.SetActive(true);
				AppLog.WriteMessage("Window Succesfully created using config.ini");
	}

#endif	



	//Setup our global font used throughout administrative engine functionality.
	float tempH = TrogWin.GetHeight() * .035;
	float tempW = TrogWin.GetWidth() * .075;
	float fontsize = tempH + tempW /2.75;
	fontsize=fontsize/2;
	CourierFont.BuildFont(fontsize,false,false,false,"Courier New");
	AppLog.WriteMessage("Our Global Font was created successfully.");

	//Initialize our global shaders.
	Tex_Shade.installShaders("../resources/shaders/texture.vert",
			"../resources/shaders/texture.frag");
	AppLog.WriteMessage("Texture shader Loaded into memory.");

	//Start the main Loop
	AppLog.WriteMessage("Entering Main Game Loop.");
	while(!done)	
	{

		if (PeekMessage(&msg,NULL,0,0,PM_REMOVE))		//Poll for Windows Messages
		{

			if (msg.message==WM_QUIT)
			{
				done=true;					
			}
			else							
			{

				TranslateMessage(&msg);				// Translate The Message
				DispatchMessage(&msg);				// Dispatch The Message
			}
		}
		else								//Otherwise update GameStates
		{

			
			if (TrogWin.GetActive())						
			{

#ifdef DEBUG
				if (TrogWin.keys[VK_ESCAPE])				
				{
					done=true;			
					AppLog.WriteMessage("User Pressed Escape - Requesting Application Stop.");
				}
#endif

				if(TrogWin.GetActive())					// Update The Input/Audio/Visual Renderings
				{

					Gamepads.UpdateStates();
					MainAudio.UpdateListenerValues();
					MainState.UpdateStates();
					
				}
			}

		}
	}

	AppLog.WriteMessage("Exiting Main Game Loop.");
	// Shutdown

	CourierFont.KillFont(); //Release global Font
	AppLog.WriteMessage("Global Font Released.");
	
	
	if(argv)                //Release Python
	{
		delete argv;
		argv = NULL;
	}

	
	    
	Gamepads.FreeDirectInput(); //Release Gamepads
	AppLog.WriteMessage("DirectInput Released.");
	MainAudio.ExitOpenAL(); //Release The SOund
	AppLog.WriteMessage("OpenAL Released.");
	

#ifndef DEBUG
	Py_Finalize(); //Crashes in debug because not using debug .lib
	AppLog.WriteMessage("Python Released.");
#endif
	TrogWin.KillGLWindow();	//Release the Window  
	AppLog.WriteMessage("Window Was Released. Program Exited.");
	double result = EngineTime.CalcTimePassed();
	string Apptime = FM.Seconds_2TimeString(result);
	AppLog.WriteMessage("Engine Ran for "+Apptime);

	//Close our log files. Finalize checks to see if they exist.
	
	AppLog.Finalize();
	ErrorLog.Finalize();
	InputLog_Gamepads.Finalize();
	InputLog_Mouse.Finalize();
	InputLog_Keyboard.Finalize();
	ObjectsLog.Finalize();
	ScenesLog.Finalize();
	Log_Index.Finalize();

	return(msg.wParam);							// Exit The Program
}
Ejemplo n.º 18
0
int CallPy()
{
	Py_Initialize();
	if (!Py_IsInitialized())
		return -1;

	//c调用python:
	//直接执行python脚本
	PyRun_SimpleString("import sys");
	PyRun_SimpleString("sys.path.append('./')");

	//导入模块
	PyObject* pTestModule = PyImport_ImportModule("testpy");
	if (!pTestModule) {
		printf("Cant open python file!\n");
		return -1;
	}

	//模块的字典列表
	PyObject* pDict = PyModule_GetDict(pTestModule);
	if (!pDict) {
		printf("Cant find dictionary.\n");
		return -1;
	}

	//打印模块的字典
	printDict(pDict);

	//演示函数调用
	PyObject* pFunHi = PyDict_GetItemString(pDict, "HelloWorld");
	PyObject_CallFunction(pFunHi, "s", "Hello World!");
	//Py_DECREF(pFunHi);	//不用减少引用计数
	//Py_DECREF(pDict);
	Py_DECREF(pTestModule);

	/*********************************************************************/
	//python 调用c:
	//手动导入cmodule到python环境
	initcmodule();
	//直接脚本调用,验证python已经导入cmodule模块
	PyRun_SimpleString("import cmodule");
	PyRun_SimpleString("print 'call in python: ', cmodule.print_info(123)");
	//程序调用
	PyObject* pCmodule = PyImport_ImportModule("cmodule");
	PyObject* cprint_info = PyObject_GetAttrString(pCmodule, "print_info");
	if (!PyCallable_Check(cprint_info)) {
		PyErr_SetString(PyExc_TypeError, "parameter must be callable");
		return NULL;
	}
	int iarg = 9;
	PyObject* result = PyObject_CallFunction(cprint_info, "i", iarg) ;
	if (result == NULL) {
		return -1;
	}
	int i = 0, i2 = 0;
	int ok = PyArg_ParseTuple(result, "ii", &i,&i2);		//返回多个参数
	//i = PyInt_AsLong(result);								//返回一个参数
	printf("cmodule return: %d %d %d \n", ok, i, i2);

	Py_DECREF(result);
	Py_DECREF(cprint_info);
	Py_DECREF(pCmodule);

	Py_Finalize();  
	return 0;
}
Ejemplo n.º 19
0
int main(int argc, char **argv)
{
	Py_Initialize();

	PyRun_SimpleString("import sys");
	PyRun_SimpleString("import os");
	PyRun_SimpleString("import time");
	PyRun_SimpleString("import io");
	PyRun_SimpleString("import socket");
	//PyRun_SimpleString("print(os.getcwd())");
	PyRun_SimpleString("sys.path.append(os.getcwd())");
	PyRun_SimpleString("import buildtcp");

	//int ret =  PyRun_SimpleFile(fp, "./buildtcp.py");
	PyObject *main_module = PyImport_AddModule("__main__");
	PyObject *target = PyImport_AddModule("buildtcp");
	if(!main_module) {
		printf("failed to PyImport_AddModule()\n");
		return 0;
	}

	PyObject *g_dict = PyModule_GetDict(main_module);
	PyObject *l_dict = PyDict_New();
	if(!l_dict) {
		printf("failed to PyDict_New()\n");
		return 0;
	}

	FILE *fp = fopen("./buildtcp.py", "r");
	//PyObject *res = PyRun_File(fp, "./buildtcp.py", Py_file_input, g_dict, l_dict);
	//PyObject *res = PyRun_File(fp, "./buildtcp.py", Py_file_input, g_dict, g_dict);
	//PyObject *res = PyRun_String("buildtcp.buildtcp()", Py_file_input, g_dict, l_dict);
	printf("PyDict_Size(g_dict):%d\n", PyDict_Size(g_dict));
	print_dict(g_dict);
	printf("PyDict_Size(l_dict):%d\n", PyDict_Size(l_dict));
	print_dict(l_dict);
	//PyObject *key = PyUnicode_FromString("buildtcp");
	//PyObject *func = PyDict_GetItem(l_dict, key);
	//PyObject* f_str_exc_type = PyObject_Repr(func);
	//PyObject* f_pyStr = PyUnicode_AsEncodedString(f_str_exc_type, "utf-8", "Error ~");
	//printf("value:%s\n", PyBytes_AsString(f_pyStr));
	//res = PyObject_Call(func, PyTuple_New(), NULL);
	//res = PyObject_CallObject(func, NULL);
	PyObject *res = PyObject_CallMethodObjArgs(target, PyUnicode_FromString("buildtcp"), NULL);
	if(!res) {
		printf("failed to PyRun_File()\n");
		return 0;
	}

	if(!PyObject_CheckBuffer(res)) {
		printf("res is not Py_buffer\n");
		return 0;
	}

	Py_buffer buf;
	int ret = PyObject_GetBuffer(res, &buf, PyBUF_SIMPLE);
	if(ret == -1) {
		printf("failed to PyObject_GetBuffer()\n");
		return 0;
	}
	hexdump("return val", buf.buf, buf.len);

	fclose(fp);
	Py_Finalize();

	return 0;
}
Ejemplo n.º 20
0
static void
main_thread(int port)
{
    int sock, conn, size, i;
    struct sockaddr_in addr, clientaddr;

    sock = socket(PF_INET, SOCK_STREAM, 0);
    if (sock < 0) {
        oprogname();
        perror("can't create socket");
        exit(1);
    }

#ifdef SO_REUSEADDR
    i = 1;
    setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char *) &i, sizeof i);
#endif

    memset((char *)&addr, '\0', sizeof addr);
    addr.sin_family = AF_INET;
    addr.sin_port = htons(port);
    addr.sin_addr.s_addr = 0L;
    if (bind(sock, (struct sockaddr *)&addr, sizeof addr) < 0) {
        oprogname();
        perror("can't bind socket to address");
        exit(1);
    }

    if (listen(sock, 5) < 0) {
        oprogname();
        perror("can't listen on socket");
        exit(1);
    }

    fprintf(stderr, "Listening on port %d...\n", port);

    for (i = 0; ; i++) {
        size = sizeof clientaddr;
        memset((char *) &clientaddr, '\0', size);
        conn = accept(sock, (struct sockaddr *) &clientaddr, &size);
        if (conn < 0) {
            oprogname();
            perror("can't accept connection from socket");
            exit(1);
        }

        size = sizeof addr;
        memset((char *) &addr, '\0', size);
        if (getsockname(conn, (struct sockaddr *)&addr, &size) < 0) {
            oprogname();
            perror("can't get socket name of connection");
            exit(1);
        }
        if (clientaddr.sin_addr.s_addr != addr.sin_addr.s_addr) {
            oprogname();
            perror("connection from non-local host refused");
            fprintf(stderr, "(addr=%lx, clientaddr=%lx)\n",
                ntohl(addr.sin_addr.s_addr),
                ntohl(clientaddr.sin_addr.s_addr));
            close(conn);
            continue;
        }
        if (i == 4) {
            close(conn);
            break;
        }
        create_thread(conn, &clientaddr);
    }

    close(sock);

    if (gtstate) {
        PyEval_AcquireThread(gtstate);
        gtstate = NULL;
        Py_Finalize();
        /* And a second time, just because we can. */
        Py_Finalize(); /* This should be harmless. */
    }
    exit(0);
}
Ejemplo n.º 21
0
/* int main(int argc, char **argv) { */
int main(int argc, char *argv[]) {

  char *env_argument = NULL;
  char *env_entrypoint = NULL;
  char *env_logname = NULL;
  char entrypoint[ENTRYPOINT_MAXLEN];
  int ret = 0;
  FILE *fd;

  /* AND: Several filepaths are hardcoded here, these must be made
     configurable */
  /* AND: P4A uses env vars...not sure what's best */
  LOGP("Initialize Python for Android");
  env_argument = getenv("ANDROID_ARGUMENT");
  setenv("ANDROID_APP_PATH", env_argument, 1);
  env_entrypoint = getenv("ANDROID_ENTRYPOINT");
  env_logname = getenv("PYTHON_NAME");
  
  if (env_logname == NULL) {
    env_logname = "python";
    setenv("PYTHON_NAME", "python", 1);
  }

  LOGP("Changing directory to the one provided by ANDROID_ARGUMENT");
  LOGP(env_argument);
  chdir(env_argument);

  Py_SetProgramName(L"android_python");

#if PY_MAJOR_VERSION >= 3
  /* our logging module for android
   */
  PyImport_AppendInittab("androidembed", initandroidembed);
#endif

  LOGP("Preparing to initialize python");

  if (dir_exists("crystax_python/")) {
    LOGP("crystax_python exists");
    char paths[256];
    snprintf(paths, 256,
             "%s/crystax_python/stdlib.zip:%s/crystax_python/modules",
             env_argument, env_argument);
    /* snprintf(paths, 256, "%s/stdlib.zip:%s/modules", env_argument,
     * env_argument); */
    LOGP("calculated paths to be...");
    LOGP(paths);

#if PY_MAJOR_VERSION >= 3
    wchar_t *wchar_paths = Py_DecodeLocale(paths, NULL);
    Py_SetPath(wchar_paths);
#else
    char *wchar_paths = paths;
    LOGP("Can't Py_SetPath in python2, so crystax python2 doesn't work yet");
    exit(1);
#endif

    LOGP("set wchar paths...");
  } else {
    LOGP("crystax_python does not exist");
  }

  Py_Initialize();

#if PY_MAJOR_VERSION < 3
  PySys_SetArgv(argc, argv);
#endif

  LOGP("Initialized python");

  /* ensure threads will work.
   */
  LOGP("AND: Init threads");
  PyEval_InitThreads();

#if PY_MAJOR_VERSION < 3
  initandroidembed();
#endif

  PyRun_SimpleString("import androidembed\nandroidembed.log('testing python "
                     "print redirection')");

  /* inject our bootstrap code to redirect python stdin/stdout
   * replace sys.path with our path
   */
  PyRun_SimpleString("import sys, posix\n");
  if (dir_exists("lib")) {
    /* If we built our own python, set up the paths correctly */
    LOGP("Setting up python from ANDROID_PRIVATE");
    PyRun_SimpleString("private = posix.environ['ANDROID_PRIVATE']\n"
                       "argument = posix.environ['ANDROID_ARGUMENT']\n"
                       "sys.path[:] = [ \n"
                       "    private + '/lib/python27.zip', \n"
                       "    private + '/lib/python2.7/', \n"
                       "    private + '/lib/python2.7/lib-dynload/', \n"
                       "    private + '/lib/python2.7/site-packages/', \n"
                       "    argument ]\n");
  }

  if (dir_exists("crystax_python")) {
    char add_site_packages_dir[256];
    snprintf(add_site_packages_dir, 256,
             "sys.path.append('%s/crystax_python/site-packages')",
             env_argument);

    PyRun_SimpleString("import sys\n"
                       "sys.argv = ['notaninterpreterreally']\n"
                       "from os.path import realpath, join, dirname");
    PyRun_SimpleString(add_site_packages_dir);
    /* "sys.path.append(join(dirname(realpath(__file__)), 'site-packages'))") */
    PyRun_SimpleString("sys.path = ['.'] + sys.path");
  }

  PyRun_SimpleString(
      "class LogFile(object):\n"
      "    def __init__(self):\n"
      "        self.buffer = ''\n"
      "    def write(self, s):\n"
      "        s = self.buffer + s\n"
      "        lines = s.split(\"\\n\")\n"
      "        for l in lines[:-1]:\n"
      "            androidembed.log(l)\n"
      "        self.buffer = lines[-1]\n"
      "    def flush(self):\n"
      "        return\n"
      "sys.stdout = sys.stderr = LogFile()\n"
      "print('Android path', sys.path)\n"
      "import os\n"
      "print('os.environ is', os.environ)\n"
      "print('Android kivy bootstrap done. __name__ is', __name__)");

#if PY_MAJOR_VERSION < 3
  PyRun_SimpleString("import site; print site.getsitepackages()\n");
#endif

  LOGP("AND: Ran string");

  /* run it !
   */
  LOGP("Run user program, change dir and execute entrypoint");

  /* Get the entrypoint, search the .pyo then .py
   */
  char *dot = strrchr(env_entrypoint, '.');
  if (dot <= 0) {
    LOGP("Invalid entrypoint, abort.");
    return -1;
  }
  if (strlen(env_entrypoint) > ENTRYPOINT_MAXLEN - 2) {
      LOGP("Entrypoint path is too long, try increasing ENTRYPOINT_MAXLEN.");
      return -1;
  }
  if (!strcmp(dot, ".pyo")) {
    if (!file_exists(env_entrypoint)) {
      /* fallback on .py */
      strcpy(entrypoint, env_entrypoint);
      entrypoint[strlen(env_entrypoint) - 1] = '\0';
      LOGP(entrypoint);
      if (!file_exists(entrypoint)) {
        LOGP("Entrypoint not found (.pyo, fallback on .py), abort");
        return -1;
      }
    } else {
      strcpy(entrypoint, env_entrypoint);
    }
  } else if (!strcmp(dot, ".py")) {
    /* if .py is passed, check the pyo version first */
    strcpy(entrypoint, env_entrypoint);
    entrypoint[strlen(env_entrypoint) + 1] = '\0';
    entrypoint[strlen(env_entrypoint)] = 'o';
    if (!file_exists(entrypoint)) {
      /* fallback on pure python version */
      if (!file_exists(env_entrypoint)) {
        LOGP("Entrypoint not found (.py), abort.");
        return -1;
      }
      strcpy(entrypoint, env_entrypoint);
    }
  } else {
    LOGP("Entrypoint have an invalid extension (must be .py or .pyo), abort.");
    return -1;
  }
  // LOGP("Entrypoint is:");
  // LOGP(entrypoint);
  fd = fopen(entrypoint, "r");
  if (fd == NULL) {
    LOGP("Open the entrypoint failed");
    LOGP(entrypoint);
    return -1;
  }

  /* run python !
   */
  ret = PyRun_SimpleFile(fd, entrypoint);

  if (PyErr_Occurred() != NULL) {
    ret = 1;
    PyErr_Print(); /* This exits with the right code if SystemExit. */
    PyObject *f = PySys_GetObject("stdout");
    if (PyFile_WriteString(
            "\n", f)) /* python2 used Py_FlushLine, but this no longer exists */
      PyErr_Clear();
  }

  /* close everything
   */
  Py_Finalize();
  fclose(fd);

  LOGP("Python for android ended.");
  return ret;
}
Ejemplo n.º 22
0
int main(int argc, char *argv[])
{
	
    
	//\================================================================================================
	//\ Initialise Python
	//\================================================================================================
	Py_Initialize();
	//\================================================================================================
	//\Add our current directory to the path lookup for Python imports
	//\================================================================================================
	PySys_SetArgv(argc, argv);
	//PyRun_SimpleString( "from sys import path\nfrom os import getcwd\nprint \"Current Dir\" \, getcwd()\npath.append( getcwd() + \"/scripts\" )\n" );
	PyObject* sysPath = PySys_GetObject((char*)"path");
	PyList_Append(sysPath, PyString_FromString("./scripts"));
	//\================================================================================================
	//\Import the AIE C Functions into Python so that we can call them from there
	//\ we will need to add "import AIE" to any Python files that we wish to use these functions in
	//\================================================================================================
	Py_InitModule("AIE", AIE_Functions);
	//\================================================================================================
	//\ Here we are loading our Python Entry point this is the name of the game.py file that we will be 
	//\ using for this project.
	//\ ** feel free to change this to anything you would like to, "game" is purely intended as a 
	//\    suitable example.
	//\================================================================================================

	//PyObject* pModule = ImportPythonModule("VMGameGrid");

	PyObject* pModule = ImportPythonModule("game");
	
	if (pModule != NULL) 
	{
		//\============================================================================================
		//\ Here we are attempting to resolve a function to call inside our python file
		//\ In this scenario we are looking for the main function inside our game.py file
		//\============================================================================================
		if( AIE::InitialiseFramework( pModule ) )
		{
			AIE::Load(pModule);
			do 
			{

				ClearScreen();
				float fDeltaTime = GetDeltaTime();
				AIE::UpdatePython( pModule, fDeltaTime );
				

			}while( !FrameworkUpdate() );

			AIE::ShutdownFramework( pModule );
		}
		Py_DECREF(pModule);
    }
    Py_Finalize();

	if( g_pWindowTitle )
	{
		delete[] g_pWindowTitle;
	}

    return 0;
}
Ejemplo n.º 23
0
/** Ends the Python interpreter, freeing resources*/
static void python_system_exit(lua_State *L) {
    if (Py_IsInitialized() && python_getnumber(L, PY_API_IS_EMBEDDED))
        Py_Finalize();
}
Ejemplo n.º 24
0
int
main()
{
	// initial the interpreter
    char xv[100] = "abcdefg";
    PyObject * tstr = PyString_FromString(xv);
	Py_Initialize();
	if (!Py_IsInitialized()) {
		return -1;
	}
	// import the sys module
	PyRun_SimpleString("import sys");
	// add the current path to sys.path
	PyRun_SimpleString("sys.path.append('./')");

	PyObject * pModule = NULL;
	PyObject * pFunc = NULL;
	PyObject * pName = NULL;
	PyObject * pModule1 = NULL;
	PyObject * pFunc1 = NULL;
	PyObject * pDict = NULL;
	PyObject * pArgs = NULL;
    PyObject * pFunc2 = NULL;

	pName = PyString_FromString("pytest");
	pModule1 = PyImport_Import(pName);
	if (!pModule1) {
		printf("can't find pytest.py");
		getchar();
		return -1;
	}
	pDict = PyModule_GetDict(pModule1);
	if (!pDict) {
		return -1;
	}
	pFunc1 = PyDict_GetItemString(pDict, "add");
	if (!pFunc1 || !PyCallable_Check(pFunc1)) {
		printf("can't find function [add]");
		getchar();
		return -1;
	}
    pFunc2 = PyDict_GetItemString(pDict, "echo");
    if (!pFunc2 || !PyCallable_Check(pFunc2)) {
        printf("can't find function [echo]");
        getchar();
        return -1;
    }
    pArgs = PyTuple_New(1);
    printf("array size = %d \n", PyTuple_Size(pArgs));
    PyTuple_SetItem(pArgs, 0, tstr);
    PyObject_CallObject(pFunc2, pArgs);
	// create a Tuple(2)
	pArgs = PyTuple_New(2);
	// create long int and make Tumple points it
	PyTuple_SetItem(pArgs, 0, Py_BuildValue("l", 3));
	PyTuple_SetItem(pArgs, 1, Py_BuildValue("l", 4));
	// call a function with parameters
	PyObject_CallObject(pFunc1, pArgs);
	// reuse the pFunc1 parameter
	pFunc1 = PyDict_GetItemString(pDict, "foo");
	if(!pFunc1 || !PyCallable_Check(pFunc1)) {
		printf("can't find function [foo]");
		getchar();
		return -1;
	}
	pArgs = PyTuple_New(1);
	PyTuple_SetItem(pArgs, 0, Py_BuildValue("l", 2));
	PyObject_CallObject(pFunc1, pArgs);
	// a another way to import a module
	pModule = PyImport_ImportModule("helloworld");
	// find a function in a module
	pFunc = PyObject_GetAttrString(pModule, "hello");
	// call the function
	PyEval_CallObject(pFunc, NULL);

	// free the memory
	Py_DECREF(pName);
	Py_DECREF(pArgs);
	Py_DECREF(pModule1);
	Py_DECREF(pModule);
	// close python, release the resource
	Py_Finalize();

	return 0;
}
Ejemplo n.º 25
0
int c_function(int *n, float **mat)
{
  PyObject *pModule  = NULL;
  PyObject *pFunc = NULL;
  PyObject *pArg = NULL;
  PyObject *pRet = NULL;
  PyObject *pName = NULL;

  size_t size = *n;
  npy_intp *dim;
  int i, j;

  dim = (npy_intp *) malloc(sizeof(npy_intp)*(size));

  for (i=0; i < size; i++) dim[i] = size;

  Py_Initialize();

  if (!Py_IsInitialized())
  {
    fprintf(stderr, "nao foi possivel inicializar o python!\n");
    return -1;
  }

  init_numpy(); 

  PyObject* pMat = PyArray_NewFromDescr(
     &PyArray_Type, PyArray_DescrFromType(NPY_FLOAT), 
     2, dim, NULL, (void *) *mat, NPY_ARRAY_INOUT_FARRAY, NULL);

  Py_INCREF(pMat);

  pName = PyString_FromString("function");
  pModule = PyImport_Import(pName);

  pFunc = PyObject_GetAttrString(pModule, "py_function");

  if(!PyCallable_Check(pFunc))
  {
    printf("func not callable!\n");
    return -1;
  }

  pArg = PyTuple_New (2);
  PyTuple_SetItem(pArg, 0, (PyObject *) PyInt_FromLong(size));
  PyTuple_SetItem(pArg, 1, pMat);

  pRet = PyObject_CallObject(pFunc, pArg);

  printf("py ret: %s\n", PyString_AsString(pRet));

  Py_DECREF (pMat);
  Py_DECREF (pName);
  Py_DECREF (pModule);
  Py_DECREF (pFunc);
  Py_DECREF (pArg);
  Py_DECREF (pRet);

  Py_Finalize();

  return 0;
}
Ejemplo n.º 26
0
int AppMain()
{
	std::wstring exe_dir;

	// Get exe's directory
	{
		wchar_t exe_path_buf[MAX_PATH + 1];
		GetModuleFileName(NULL, exe_path_buf, MAX_PATH);

		exe_dir = exe_path_buf;

		size_t last_backslash_pos = exe_dir.find_last_of(L"\\/");
		if (last_backslash_pos >= 0)
		{
			exe_dir = exe_dir.substr(0, last_backslash_pos);
		}
		else
		{
			exe_dir = L"";
		}
	}

	// Setup environment variable "PATH"
	{
		std::wstring env_path;

		wchar_t tmp_buf[1];
		DWORD ret = GetEnvironmentVariable(L"PATH", tmp_buf, 0);
		if (ret > 0)
		{
			DWORD len = ret;
			wchar_t * buf = (wchar_t*)malloc((len + 1) * sizeof(wchar_t));

			GetEnvironmentVariable(L"PATH", buf, (len + 1) * sizeof(wchar_t));

			env_path = buf;

			free(buf);
		}

		env_path = exe_dir + L"/lib;" + env_path;

		SetEnvironmentVariable(L"PATH", env_path.c_str());
	}

	// Python home
	{
#if defined(_DEBUG)
		Py_SetPythonHome(PYTHON_INSTALL_PATH);
#else
		Py_SetPythonHome(const_cast<wchar_t*>(exe_dir.c_str()));
#endif //_DEBUG
	}

	// Python module search path
	{
		std::wstring python_path;

		python_path += exe_dir + L"/extension;";
		
		#if defined(_DEBUG)
		python_path += exe_dir + L";";
		python_path += exe_dir + L"/..;";
		python_path += std::wstring(PYTHON_INSTALL_PATH) + L"\\Lib;";
		python_path += std::wstring(PYTHON_INSTALL_PATH) + L"\\Lib\\site-packages;";
		python_path += std::wstring(PYTHON_INSTALL_PATH) + L"\\DLLs;";
		#else
		python_path += exe_dir + L"/library.zip;";
		python_path += exe_dir + L"/lib;";
		#endif
		
		Py_SetPath(python_path.c_str());
	}

	// Initialization
	Py_Initialize();

	// Setup sys.argv
	{
		wchar_t * cmdline = GetCommandLine();

		int argc;
		wchar_t ** argv = CommandLineToArgvW(cmdline, &argc);

		PySys_SetArgv(argc, argv);

		LocalFree(argv);
	}

	// Execute python side main script
	{
		PyObject * module = PyImport_ImportModule("cmemo_main");
		if (module == NULL)
		{
			PyErr_Print();
		}

		Py_XDECREF(module);
		module = NULL;
	}

	// Termination
	Py_Finalize();

	return 0;
}
Ejemplo n.º 27
0
int main()
{
	s_erc error = S_SUCCESS;
	SList *list = NULL;
	SIterator *itr;
	SObject *a = NULL;
	SObject *b = NULL;
	SObject *c = NULL;
	PyObject *speectModule = NULL; /* for SWIG functions to work */


	/* Initialize the Python interpreter.  Required. */
    Py_Initialize();

	/* import speect python module */
	speectModule = PyImport_ImportModule("speect");
	if (speectModule == NULL)
	{
		char *py_error = s_get_python_error_str();

		if (py_error)
		{
			S_CTX_ERR(&error, S_FAILURE,
					  "main",
					  "Call to \"PyImport_ImportModule\" failed. Reported error: %s",
					  py_error);
			S_FREE(py_error);
		}
		else
		{
			S_CTX_ERR(&error, S_FAILURE,
					  "main",
					  "Call to \"PyImport_ImportModule\" failed");
		}

		goto quit;
	}

	/*
	 * initialize speect python native module
	 */
	error = s_python_native_objects_init();
	if (error != S_SUCCESS)
	{
		printf("Failed to initialize Speect Python native module\n");
		goto quit;
	}

	/* Create and populate Python list */
	list = create_and_populate_py_list(&error);
	if (S_CHK_ERR(&error, S_CONTERR,
				  "main",
				  "Call to \"create_and_populate_py_list\" failed"))
		goto quit;

	/*
	 * get iterator to list, should be NULL as there are no objects
	 * in the list
	 */
	itr = S_ITERATOR_GET(list, &error);
	if (S_CHK_ERR(&error, S_CONTERR,
				  "main",
				  "Failed to get iterator to list"))
		goto quit;

	/* Create some objects and put the into the list */
	a = SObjectSetInt(10, &error);
	if (S_CHK_ERR(&error, S_CONTERR,
				  "main",
				  "Failed to set int object"))
		goto quit;

	b = SObjectSetFloat(3.14, &error);
	if (S_CHK_ERR(&error, S_CONTERR,
				  "main",
				  "Failed to set float object"))
		goto quit;

	c = SObjectSetString("python list test", &error);
	if (S_CHK_ERR(&error, S_CONTERR,
				  "main",
				  "Failed to set string object"))
		goto quit;

	SListPush(list, a, &error);
	if (S_CHK_ERR(&error, S_CONTERR,
				  "main",
				  "Failed to add object to list"))
		goto quit;
	else
		a = NULL; /* object belongs to list now, we don't want to
				   * delete it directly.
				   */

	SListPush(list, b, &error);
	if (S_CHK_ERR(&error, S_CONTERR,
				  "main",
				  "Failed to add object to list"))
		goto quit;
	else
		b = NULL; /* object belongs to list now, we don't want to
				   * delete it directly.
				   */

	SListPush(list, c, &error);
	if (S_CHK_ERR(&error, S_CONTERR,
				  "main",
				  "Failed to add object to list"))
		goto quit;
	else
		c = NULL; /* object belongs to list now, we don't want to
				   * delete it directly.
				   */

	/*
	 * get iterator to list, should not be NULL as there are now
	 * objects in the list
	 */
	itr = S_ITERATOR_GET(list, &error);
	if (S_CHK_ERR(&error, S_CONTERR,
				  "main",
				  "Failed to get iterator to list"))
		goto quit;

	/* iterate through list objects and print them to stdout */
	for (/* NOP */; itr != NULL; itr = SIteratorNext(itr))
	{
		char *buf;
		const SObject *tmp;


		tmp = SIteratorObject(itr, &error);
		if (S_CHK_ERR(&error,  S_CONTERR,
					  "main",
					  "Failed to get list iterator object"))
			goto quit;

		buf = SObjectPrint(tmp, &error);
		if (S_CHK_ERR(&error,  S_CONTERR,
					  "main",
					  "Failed to print  object"))
			goto quit;

		printf("list object = %s\n", buf);
		S_FREE(buf);
	}

quit:
	if (list != NULL)
		S_DELETE(list, "main", &error);

	if (itr != NULL)
		S_DELETE(itr, "main", &error);

	if (a != NULL)
		S_DELETE(a, "main", &error);

	if (b != NULL)
		S_DELETE(b, "main", &error);

	if (c != NULL)
		S_DELETE(c, "main", &error);

	Py_XDECREF(speectModule);
	Py_Finalize();

	return 0;
}
Ejemplo n.º 28
0
extc void __cdecl ODBG2_Plugindestroy(void)
{
    // Properly ends the python environment
    Py_Finalize();
}
Ejemplo n.º 29
0
void PyVisInterface::ShutdownPython() {
    delete g_PyVis;
    g_PyVis = NULL;
 
    Py_Finalize();
}
Ejemplo n.º 30
0
int main (int argc, char **argv)
{
	bindtextdomain (GETTEXT_PACKAGE, GNOMELOCALEDIR);
	bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
	textdomain (GETTEXT_PACKAGE);

	if (!Glib::thread_supported())
		Glib::thread_init(0); //So we can use GMutex.
	Gnome::Conf::init();

	std::auto_ptr<Gtk::Main> mainInstance;
	try
	{
		mainInstance = std::auto_ptr<Gtk::Main>( new Gtk::Main(argc, argv) );
	}
	catch(const Glib::Error& ex)
	{
		std::cerr << "Glom: Error while initializing gtkmm: " << ex.what() << std::endl;
		return EXIT_FAILURE;
	}

	Gio::init ();

	Glib::ustring pythonPath = "";
	/* Pick up existing python path */
	if (getenv("PYTHONPATH")) {
		pythonPath += ":";
		pythonPath += getenv("PYTHONPATH");
	}

	/* Locate user plugins */
	Glib::ustring homePlugins;
	if (getenv("HOME"))
		homePlugins = Glib::ustring(getenv("HOME")) + Glib::ustring("/.referencer/plugins");

	/* Development directory */
	Glib::ustring localPlugins = "./plugins";
	/* Systemwide */
	Glib::ustring installedPlugins = PLUGINDIR;

	/* Order is important, defines precedence */
	pythonPath += ":";
	pythonPath += localPlugins;
	pythonPath += ":";
	pythonPath += homePlugins;
	pythonPath += ":";
	pythonPath += installedPlugins;
	pythonPath += ":";
	/* Export the path */
	DEBUG (String::ucompose ("setting pythonPath to %1", pythonPath));
	setenv ("PYTHONPATH", pythonPath.c_str(), 1);
	Py_Initialize ();

	_global_plugins = new PluginManager ();
	_global_plugins->scan("./plugins");
	_global_plugins->scan(homePlugins);
	_global_plugins->scan(PLUGINDIR);

	_global_prefs = new Preferences();

	if (argc > 1 && Glib::ustring(argv[1]).substr(0,1) != "-") {
		Glib::RefPtr<Gio::File> libfile = Gio::File::create_for_commandline_arg(argv[1]);

		_global_prefs->setLibraryFilename (libfile->get_uri());
	}

	try {
		RefWindow window;
		window.run();
	} catch (Glib::Error ex) {
		Utility::exceptionDialog (&ex, _("Terminating due to unhandled exception"));
	}

	delete _global_prefs;
	delete _global_plugins;
	Py_Finalize ();

	return 0;
}