示例#1
0
py_state_t *py_state_new(const char *script, unsigned is_file, const char *pyclass)
{
   RARCH_LOG("Initializing Python runtime ...\n");
   PyImport_AppendInittab("rarch", &PyInit_Retro);
   Py_Initialize();
   RARCH_LOG("Initialized Python runtime.\n");

   py_state_t *handle = (py_state_t*)calloc(1, sizeof(*handle));
   PyObject *hook = NULL;

   handle->main = PyImport_AddModule("__main__");
   if (!handle->main)
      goto error;
   Py_INCREF(handle->main);

   if (is_file)
   {
      // Have to hack around the fact that the
      // FILE struct isn't standardized across environments.
      // PyRun_SimpleFile() breaks on Windows because it's compiled with MSVC.

      char *script_ = NULL;
      if (read_file(script, (void**)&script_) < 0)
      {
         RARCH_ERR("Python: Failed to read script\n");
         goto error;
      }

      PyRun_SimpleString(script_);
      free(script_);
   }
   else
   {
      char *script_ = align_program(script);
      if (script_)
      {
         PyRun_SimpleString(script_);
         free(script_);
      }
   }

   RARCH_LOG("Python: Script loaded.\n");
   handle->dict = PyModule_GetDict(handle->main);
   if (!handle->dict)
   {
      RARCH_ERR("Python: PyModule_GetDict() failed.\n");
      goto error;
   }
   Py_INCREF(handle->dict);

   hook = PyDict_GetItemString(handle->dict, pyclass);
   if (!hook)
   {
      RARCH_ERR("Python: PyDict_GetItemString() failed.\n");
      goto error;
   }

   handle->inst = PyObject_CallFunction(hook, NULL);
   if (!handle->inst)
   {
      RARCH_ERR("Python: PyObject_CallFunction() failed.\n");
      goto error;
   }
   Py_INCREF(handle->inst);

   return handle;

error:
   PyErr_Print();
   PyErr_Clear();
   py_state_free(handle);
   return NULL;
}
示例#2
0
PythonEval::PythonEval() {
	PyImport_AppendInittab("emb", &PyInit_emb);
	Py_Initialize();
}
示例#3
0
文件: capis.cpp 项目: finaldie/skull
void register_capis() {
    PyImport_AppendInittab("skull_capi", PyInit_capi);
}
示例#4
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__)");

    /* 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;
}
示例#5
0
/**
 * Initialize libsigrokdecode.
 *
 * This initializes the Python interpreter, and creates and initializes
 * a "sigrokdecode" Python module.
 *
 * Then, it searches for sigrok protocol decoders in the "decoders"
 * subdirectory of the the libsigrokdecode installation directory.
 * All decoders that are found are loaded into memory and added to an
 * internal list of decoders, which can be queried via srd_decoder_list().
 *
 * The caller is responsible for calling the clean-up function srd_exit(),
 * which will properly shut down libsigrokdecode and free its allocated memory.
 *
 * Multiple calls to srd_init(), without calling srd_exit() in between,
 * are not allowed.
 *
 * @param path Path to an extra directory containing protocol decoders
 *             which will be added to the Python sys.path. May be NULL.
 *
 * @return SRD_OK upon success, a (negative) error code otherwise.
 *         Upon Python errors, SRD_ERR_PYTHON is returned. If the decoders
 *         directory cannot be accessed, SRD_ERR_DECODERS_DIR is returned.
 *         If not enough memory could be allocated, SRD_ERR_MALLOC is returned.
 *
 * @since 0.1.0
 */
SRD_API int srd_init(const char *path)
{
	const char *const *sys_datadirs;
	const char *env_path;
	size_t i;
	int ret;

	if (max_session_id != -1) {
		srd_err("libsigrokdecode is already initialized.");
		return SRD_ERR;
	}

	srd_dbg("Initializing libsigrokdecode.");

	/* Add our own module to the list of built-in modules. */
	PyImport_AppendInittab("sigrokdecode", PyInit_sigrokdecode);

	/* Initialize the Python interpreter. */
	Py_InitializeEx(0);

	/* Locations relative to the XDG system data directories. */
	sys_datadirs = g_get_system_data_dirs();
	for (i = g_strv_length((char **)sys_datadirs); i > 0; i--) {
		ret = searchpath_add_xdg_dir(sys_datadirs[i-1]);
		if (ret != SRD_OK) {
			Py_Finalize();
			return ret;
		}
	}
#ifdef DECODERS_DIR
	/* Hardcoded decoders install location, if defined. */
	if ((ret = srd_decoder_searchpath_add(DECODERS_DIR)) != SRD_OK) {
		Py_Finalize();
		return ret;
	}
#endif
	/* Location relative to the XDG user data directory. */
	ret = searchpath_add_xdg_dir(g_get_user_data_dir());
	if (ret != SRD_OK) {
		Py_Finalize();
		return ret;
	}

	/* Path specified by the user. */
	if (path) {
		if ((ret = srd_decoder_searchpath_add(path)) != SRD_OK) {
			Py_Finalize();
			return ret;
		}
	}

	/* Environment variable overrides everything, for debugging. */
	if ((env_path = g_getenv("SIGROKDECODE_DIR"))) {
		if ((ret = srd_decoder_searchpath_add(env_path)) != SRD_OK) {
			Py_Finalize();
			return ret;
		}
	}

	max_session_id = 0;

	return SRD_OK;
}
示例#6
0
int
weechat_plugin_init (struct t_weechat_plugin *plugin, int argc, char *argv[])
{
    struct t_plugin_script_init init;

    weechat_python_plugin = plugin;

    /*
     * hook info to get path to python 2.x interpreter
     * (some scripts using hook_process need that)
     */
    weechat_python_set_python2_bin ();
    weechat_hook_info ("python2_bin",
                       N_("path to python 2.x interpreter"),
                       NULL,
                       &weechat_python_info_cb, NULL);

    /* init stdout/stderr buffer */
    python_buffer_output[0] = '\0';

    PyImport_AppendInittab("weechat",
                           &weechat_python_init_module_weechat);

    Py_Initialize ();
    if (Py_IsInitialized () == 0)
    {
        weechat_printf (NULL,
                        weechat_gettext ("%s%s: unable to launch global "
                                         "interpreter"),
                        weechat_prefix ("error"), PYTHON_PLUGIN_NAME);
        return WEECHAT_RC_ERROR;
    }

    /* PyEval_InitThreads(); */
    /* python_mainThreadState = PyThreadState_Swap(NULL); */
    python_mainThreadState = PyEval_SaveThread();
    /* PyEval_ReleaseLock (); */

    if (!python_mainThreadState)
    {
        weechat_printf (NULL,
                        weechat_gettext ("%s%s: unable to get current "
                                         "interpreter state"),
                        weechat_prefix ("error"), PYTHON_PLUGIN_NAME);
        return WEECHAT_RC_ERROR;
    }

    init.callback_command = &weechat_python_command_cb;
    init.callback_completion = &weechat_python_completion_cb;
    init.callback_hdata = &weechat_python_hdata_cb;
    init.callback_infolist = &weechat_python_infolist_cb;
    init.callback_signal_debug_dump = &weechat_python_signal_debug_dump_cb;
    init.callback_signal_debug_libs = &weechat_python_signal_debug_libs_cb;
    init.callback_signal_buffer_closed = &weechat_python_signal_buffer_closed_cb;
    init.callback_signal_script_action = &weechat_python_signal_script_action_cb;
    init.callback_load_file = &weechat_python_load_cb;

    python_quiet = 1;
    plugin_script_init (weechat_python_plugin, argc, argv, &init);
    python_quiet = 0;

    plugin_script_display_short_list (weechat_python_plugin,
                                      python_scripts);

    /* init OK */
    return WEECHAT_RC_OK;
}
示例#7
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;
}
示例#8
0
void initCdbextPythonModule()
{
    PyImport_AppendInittab("cdbext", PyInit_cdbext);
}
示例#9
0
	void InitAlembic()
	{
		PyImport_AppendInittab("mmdbridge_abc", PyInit_mmdbridge_abc);
	}
示例#10
0
void PythonInterpreter::initialize(OutputRedirector redirector)
{
    //
    // When using Boost.Python as a shared libray, Boost.Python's C++ <-> Python registry
    // is shared between all loaded Boost.Python extension modules, and objects can be
    // converted between modules.
    //
    // When using Boost.Python as a static library however, each module has its own
    // registry and attempting to convert objects between modules fails.
    //
    // To summarize:
    //  - When using compiled modules with static Boost.Python, there are 2 registries.
    //  - When using compiled modules with shared Boost.Python, there is 1 registry.
    //
    // The solution is to build all extension modules into appleseed.studio such that
    // we get a single registry. That way appleseed.studio module can find a converter
    // from e.g. renderer::Project to appleseedpython.Project.
    //

    PyImport_AppendInittab("_appleseedpythonbuiltin", init_appleseedpythonbuiltin);
    PyImport_AppendInittab("_appleseedstudio", init_appleseedstudio);
    Py_Initialize();

    bpy::object main_module = bpy::import("__main__");
    m_main_namespace = main_module.attr("__dict__");

    // Locate the path to Python's site-packages/ directory.
    const bf::path site_packages_path = compute_site_packages_path();
    if (bf::is_directory(site_packages_path))
    {
        RENDERER_LOG_INFO("Python's site-packages directory found at %s.",
            site_packages_path.string().c_str());
    }
    else
    {
        RENDERER_LOG_WARNING(
            "Python's site-packages directory does not exist: %s",
            site_packages_path.string().c_str());
    }

    // Locate the path to appleseed Python module's directory.
    const bf::path appleseed_python_module_path = compute_appleseed_python_module_path();
    if (bf::is_directory(appleseed_python_module_path))
    {
        RENDERER_LOG_INFO(
            "appleseed Python module's directory found at %s.",
            appleseed_python_module_path.string().c_str());
    }
    else
    {
        RENDERER_LOG_WARNING(
            "appleseed Python module's directory does not exist: %s",
            appleseed_python_module_path.string().c_str());
    }

    // Add paths to Python's site-packages/ and appleseed Python module's directory to sys.path.
    bpy::import("sys").attr("path").attr("append")(site_packages_path.string());
    bpy::import("sys").attr("path").attr("append")(appleseed_python_module_path.string());

    // Redirect stdout and stderr to the output panel.
    bpy::class_<OutputRedirector>("OutputRedirector", bpy::no_init)
        .def("write", &OutputRedirector::write);

    bpy::object sys_module = bpy::import("sys");
    sys_module.attr("stdout") = redirector;
    sys_module.attr("stderr") = redirector;

    // Import Python modules.
    import_python_module("appleseed", "asr");
    import_python_module("appleseed.studio", "studio");
}
示例#11
0
void Effect::registerHyperionExtensionModule()
{
	PyImport_AppendInittab("hyperion", &PyInit_hyperion);
}
示例#12
0
文件: mangopy.cpp 项目: bo0ts/mango
  void initialize(int argc, char *argv[], bool setup_default_environment){
    wchar_t **argv_copy;
    char exec_path[2048];
    char home_path[2048];
    wchar_t *wide_exec_path;
    wchar_t *wide_home_path;

    argv_copy = (wchar_t **)PyMem_Malloc(sizeof(wchar_t*)*argc);
    for (int i = 0; i < argc - 1; i++) {
      argv_copy[i] = char2wchar(argv[i + 1]);
      // todo: handle the case where argv_copy is NULL
    }

    Mango::initialize(false);

    if (setup_default_environment) {      
      Mango::GlobalFrame = new Mango::Core::Frame(true);
      Mango::Engine = new MangoPy::PyEngine();
      Mango::Keyboard = new Mango::Core::CoreKeyboard();
      Mango::Mouse = new Mango::Core::CoreMouse();
      Mango::Camera = new Mango::Core::CoreCamera();
      Mango::View = new Mango::Core::CoreCamera();      
      
      Mango::Camera->set(STEP);
      Mango::Camera->lookAt(Mango::Vector(0, 0, 0), 5);
      
      Mango::View->set(STEP);
      Mango::View->setMode(RMB_CYLINDRICAL_ROTATE | LMB_DRAG_FOCUS | ZOOM_SCALES);

      Mango::Engine->setCameraObject(Mango::Camera);
      Mango::Engine->setViewObject(Mango::View);
    }


    // Add modules - phase one
    PyImport_AppendInittab("_mpygen", PyInit__mpygen);
    PyImport_AppendInittab("Core", PyInit_Core);
    PyImport_AppendInittab("OpenGL", PyInit_OpenGL);
    PyImport_AppendInittab("Draw", PyInit_Draw);
    
    // Initialize Python    
    if (!executable_path(exec_path, 2048)){
      std::cout << "Warning: could not determine executable path." << std::endl;
      std::cout << "         using argv[0], but this value is not reliable" << std::endl;
      std::cout << "         and Mango may not be able to find or execute " << std::endl;
      std::cout << "         files outside of its own directory" << std::endl;
      strncpy(exec_path, argv[0], 2047);
      exec_path[2047] = NULL;
    }
    wide_exec_path = char2wchar(exec_path);
    // Py_SetProgramName(wide_exec_path);
       
#if !defined(WIN32)
    // Set Home Path
    // Windows seems to set exec_prefix just fine without this, so
    // it is skipped on windows until needed
    python_home_path(exec_path, home_path, 2048);
    wide_home_path = char2wchar(home_path);
    // Py_SetPythonHome(wide_home_path);       
#endif

    Py_Initialize();
    PySys_SetArgv(argc - 1, argv_copy);
    

    // Add modules - phase two
    PyObject* main_module = PyImport_AddModule("__main__");    
    PyObject *module_mpygen = PyImport_ImportModule("_mpygen");	
    Py_INCREF(module_mpygen);
    PyModule_AddObject(main_module, "_mpygen", module_mpygen);

    if (module_mpygen == NULL){
      std::cout << "MangoPy: Error creating module _mpygen" << std::endl;	
      exit(1);
    }
    
    PyObject *module_core = PyImport_ImportModule("Core");	
    Py_INCREF(module_core);
    PyModule_AddObject(main_module, "Core", module_core);
    
    if (module_core == NULL){
      std::cout << "MangoPy: Error creating module Core" << std::endl;	
      exit(1);
    }
    
    PyObject *module_opengl = PyImport_ImportModule("OpenGL");	
    Py_INCREF(module_opengl);
    PyModule_AddObject(main_module, "OpenGL", module_opengl);
    
    if (module_opengl == NULL){
      std::cout << "MangoPy: Error creating module OpenGL" << std::endl;	
      exit(1);
    }

    PyObject *module_draw = PyImport_ImportModule("Draw");	
    Py_INCREF(module_draw);
    PyModule_AddObject(main_module, "Draw", module_draw);
    
    if (module_draw == NULL){
      std::cout << "MangoPy: Error creating module Draw" << std::endl;	
      exit(1);
    }
    
    // Add absolute path to engine to the module search path
    PyRun_SimpleString("import os, sys");
    PyModule_AddStringConstant(module_core, "MANGO_LAUNCH_PATH", exec_path);
    PyRun_SimpleString("Core.MANGO_ABSOLUTE_PATH = os.path.dirname(os.path.normpath(os.path.realpath(Core.MANGO_LAUNCH_PATH)))");
    PyRun_SimpleString("sys.path.append(Core.MANGO_ABSOLUTE_PATH)");
    PyRun_SimpleString("sys.path.append(os.path.normpath(os.path.join(Core.MANGO_ABSOLUTE_PATH, '../script')))");

    // Make the Core module globally available
    PyRun_SimpleString("__builtins__._mpygen = _mpygen");
    PyRun_SimpleString("__builtins__.Core = Core");
    PyRun_SimpleString("__builtins__.Draw = Draw");
    PyRun_SimpleString("__builtins__.OpenGL = OpenGL");
    PyRun_SimpleString("__builtins__.Vector = Core.Vector");
    PyRun_SimpleString("__builtins__.STEP = Core.STEP");
    PyRun_SimpleString("__builtins__.RENDER = Core.RENDER");
    PyRun_SimpleString("__builtins__.DRAW = Core.DRAW");
    PyRun_SimpleString("__builtins__.INPUT = Core.INPUT");
    
    PyRun_SimpleString("__builtins__.CAMERA_DEFAULT_MODE = Core.CAMERA_DEFAULT_MODE");
    PyRun_SimpleString("__builtins__.LOCK_PAN = Core.LOCK_PAN");
    PyRun_SimpleString("__builtins__.LOCK_DISTANCE = Core.LOCK_DISTANCE");
    PyRun_SimpleString("__builtins__.LOCK_ALPHA = Core.LOCK_ALPHA");
    PyRun_SimpleString("__builtins__.LOCK_BETA = Core.LOCK_BETA");
    PyRun_SimpleString("__builtins__.LOCK_GAMMA = Core.LOCK_GAMMA");
    PyRun_SimpleString("__builtins__.RMB_CYLINDRICAL_ROTATE  = Core.RMB_CYLINDRICAL_ROTATE");
    PyRun_SimpleString("__builtins__.LMB_DRAG_FOCUS = Core.LMB_DRAG_FOCUS");
    PyRun_SimpleString("__builtins__.LOCK_ALL = Core.LOCK_ALL");
    
    PyRun_SimpleString("__builtins__.KEY_WINDOWS_MENU = Core.KEY_WINDOWS_MENU");
    PyRun_SimpleString("__builtins__.KEY_WINDOWS_RIGHT = Core.KEY_WINDOWS_RIGHT");
    PyRun_SimpleString("__builtins__.KEY_WINDOWS_LEFT = Core.KEY_WINDOWS_LEFT");
    PyRun_SimpleString("__builtins__.KEY_NUMPAD_DIVIDE = Core.KEY_NUMPAD_DIVIDE");
    PyRun_SimpleString("__builtins__.KEY_NUMPAD_DECIMAL = Core.KEY_NUMPAD_DECIMAL");
    PyRun_SimpleString("__builtins__.KEY_NUMPAD_SUBTRACT = Core.KEY_NUMPAD_SUBTRACT");
    PyRun_SimpleString("__builtins__.KEY_NUMPAD_SEPARATOR = Core.KEY_NUMPAD_SEPARATOR");
    PyRun_SimpleString("__builtins__.KEY_NUMPAD_ADD = Core.KEY_NUMPAD_ADD");
    PyRun_SimpleString("__builtins__.KEY_NUMPAD_MULTIPLY = Core.KEY_NUMPAD_MULTIPLY");
    PyRun_SimpleString("__builtins__.KEY_NUMPAD_EQUAL = Core.KEY_NUMPAD_EQUAL");
    PyRun_SimpleString("__builtins__.KEY_NUMPAD_DELETE = Core.KEY_NUMPAD_DELETE");
    PyRun_SimpleString("__builtins__.KEY_NUMPAD_INSERT = Core.KEY_NUMPAD_INSERT");
    PyRun_SimpleString("__builtins__.KEY_NUMPAD_BEGIN = Core.KEY_NUMPAD_BEGIN");
    PyRun_SimpleString("__builtins__.KEY_NUMPAD_END = Core.KEY_NUMPAD_END");
    PyRun_SimpleString("__builtins__.KEY_NUMPAD_PAGEDOWN = Core.KEY_NUMPAD_PAGEDOWN");
    PyRun_SimpleString("__builtins__.KEY_NUMPAD_PAGEUP = Core.KEY_NUMPAD_PAGEUP");
    PyRun_SimpleString("__builtins__.KEY_NUMPAD_DOWN = Core.KEY_NUMPAD_DOWN");
    PyRun_SimpleString("__builtins__.KEY_NUMPAD_RIGHT = Core.KEY_NUMPAD_RIGHT");
    PyRun_SimpleString("__builtins__.KEY_NUMPAD_UP = Core.KEY_NUMPAD_UP");
    PyRun_SimpleString("__builtins__.KEY_NUMPAD_LEFT = Core.KEY_NUMPAD_LEFT");
    PyRun_SimpleString("__builtins__.KEY_NUMPAD_HOME = Core.KEY_NUMPAD_HOME");
    PyRun_SimpleString("__builtins__.KEY_NUMPAD_F4 = Core.KEY_NUMPAD_F4");
    PyRun_SimpleString("__builtins__.KEY_NUMPAD_F3 = Core.KEY_NUMPAD_F3");
    PyRun_SimpleString("__builtins__.KEY_NUMPAD_F2 = Core.KEY_NUMPAD_F2");
    PyRun_SimpleString("__builtins__.KEY_NUMPAD_F1 = Core.KEY_NUMPAD_F1");
    PyRun_SimpleString("__builtins__.KEY_NUMPAD_ENTER = Core.KEY_NUMPAD_ENTER");
    PyRun_SimpleString("__builtins__.KEY_NUMPAD_TAB = Core.KEY_NUMPAD_TAB");
    PyRun_SimpleString("__builtins__.KEY_NUMPAD_SPACE = Core.KEY_NUMPAD_SPACE");
    PyRun_SimpleString("__builtins__.KEY_PAGEDOWN = Core.KEY_PAGEDOWN");
    PyRun_SimpleString("__builtins__.KEY_PAGEUP = Core.KEY_PAGEUP");
    PyRun_SimpleString("__builtins__.KEY_SCROLL = Core.KEY_SCROLL");
    PyRun_SimpleString("__builtins__.KEY_NUMLOCK = Core.KEY_NUMLOCK");
    PyRun_SimpleString("__builtins__.KEY_F24 = Core.KEY_F24");
    PyRun_SimpleString("__builtins__.KEY_F23 = Core.KEY_F23");
    PyRun_SimpleString("__builtins__.KEY_F22 = Core.KEY_F22");
    PyRun_SimpleString("__builtins__.KEY_F21 = Core.KEY_F21");
    PyRun_SimpleString("__builtins__.KEY_F20 = Core.KEY_F20");
    PyRun_SimpleString("__builtins__.KEY_F19 = Core.KEY_F19");
    PyRun_SimpleString("__builtins__.KEY_F18 = Core.KEY_F18");
    PyRun_SimpleString("__builtins__.KEY_F17 = Core.KEY_F17");
    PyRun_SimpleString("__builtins__.KEY_F16 = Core.KEY_F16");
    PyRun_SimpleString("__builtins__.KEY_F15 = Core.KEY_F15");
    PyRun_SimpleString("__builtins__.KEY_F14 = Core.KEY_F14");
    PyRun_SimpleString("__builtins__.KEY_F13 = Core.KEY_F13");
    PyRun_SimpleString("__builtins__.KEY_F12 = Core.KEY_F12");
    PyRun_SimpleString("__builtins__.KEY_F11 = Core.KEY_F11");
    PyRun_SimpleString("__builtins__.KEY_F10 = Core.KEY_F10");
    PyRun_SimpleString("__builtins__.KEY_F9 = Core.KEY_F9");
    PyRun_SimpleString("__builtins__.KEY_F8 = Core.KEY_F8");
    PyRun_SimpleString("__builtins__.KEY_F7 = Core.KEY_F7");
    PyRun_SimpleString("__builtins__.KEY_F6 = Core.KEY_F6");
    PyRun_SimpleString("__builtins__.KEY_F5 = Core.KEY_F5");
    PyRun_SimpleString("__builtins__.KEY_F4 = Core.KEY_F4");
    PyRun_SimpleString("__builtins__.KEY_F3 = Core.KEY_F3");
    PyRun_SimpleString("__builtins__.KEY_F2 = Core.KEY_F2");
    PyRun_SimpleString("__builtins__.KEY_F1 = Core.KEY_F1");
    PyRun_SimpleString("__builtins__.KEY_DIVIDE = Core.KEY_DIVIDE");
    PyRun_SimpleString("__builtins__.KEY_DECIMAL = Core.KEY_DECIMAL");
    PyRun_SimpleString("__builtins__.KEY_SUBTRACT = Core.KEY_SUBTRACT");
    PyRun_SimpleString("__builtins__.KEY_SEPARATOR = Core.KEY_SEPARATOR");
    PyRun_SimpleString("__builtins__.KEY_ADD = Core.KEY_ADD");
    PyRun_SimpleString("__builtins__.KEY_MULTIPLY = Core.KEY_MULTIPLY");
    PyRun_SimpleString("__builtins__.KEY_NUMPAD9 = Core.KEY_NUMPAD9");
    PyRun_SimpleString("__builtins__.KEY_NUMPAD8 = Core.KEY_NUMPAD8");
    PyRun_SimpleString("__builtins__.KEY_NUMPAD7 = Core.KEY_NUMPAD7");
    PyRun_SimpleString("__builtins__.KEY_NUMPAD6 = Core.KEY_NUMPAD6");
    PyRun_SimpleString("__builtins__.KEY_NUMPAD5 = Core.KEY_NUMPAD5");
    PyRun_SimpleString("__builtins__.KEY_NUMPAD4 = Core.KEY_NUMPAD4");
    PyRun_SimpleString("__builtins__.KEY_NUMPAD3 = Core.KEY_NUMPAD3");
    PyRun_SimpleString("__builtins__.KEY_NUMPAD2 = Core.KEY_NUMPAD2");
    PyRun_SimpleString("__builtins__.KEY_NUMPAD1 = Core.KEY_NUMPAD1");
    PyRun_SimpleString("__builtins__.KEY_NUMPAD0 = Core.KEY_NUMPAD0");
    PyRun_SimpleString("__builtins__.KEY_HELP = Core.KEY_HELP");
    PyRun_SimpleString("__builtins__.KEY_INSERT = Core.KEY_INSERT");
    PyRun_SimpleString("__builtins__.KEY_SNAPSHOT = Core.KEY_SNAPSHOT");
    PyRun_SimpleString("__builtins__.KEY_EXECUTE = Core.KEY_EXECUTE");
    PyRun_SimpleString("__builtins__.KEY_PRINT = Core.KEY_PRINT");
    PyRun_SimpleString("__builtins__.KEY_SELECT = Core.KEY_SELECT");
    PyRun_SimpleString("__builtins__.KEY_DOWN = Core.KEY_DOWN");
    PyRun_SimpleString("__builtins__.KEY_RIGHT = Core.KEY_RIGHT");
    PyRun_SimpleString("__builtins__.KEY_UP = Core.KEY_UP");
    PyRun_SimpleString("__builtins__.KEY_LEFT = Core.KEY_LEFT");
    PyRun_SimpleString("__builtins__.KEY_HOME = Core.KEY_HOME");
    PyRun_SimpleString("__builtins__.KEY_END = Core.KEY_END");
    PyRun_SimpleString("__builtins__.KEY_CAPITAL = Core.KEY_CAPITAL");
    PyRun_SimpleString("__builtins__.KEY_PAUSE = Core.KEY_PAUSE");
    PyRun_SimpleString("__builtins__.KEY_MENU = Core.KEY_MENU");
    PyRun_SimpleString("__builtins__.KEY_CONTROL = Core.KEY_CONTROL");
    PyRun_SimpleString("__builtins__.KEY_ALT = Core.KEY_ALT");
    PyRun_SimpleString("__builtins__.KEY_SHIFT = Core.KEY_SHIFT");
    PyRun_SimpleString("__builtins__.KEY_CLEAR = Core.KEY_CLEAR");
    PyRun_SimpleString("__builtins__.KEY_MBUTTON = Core.KEY_MBUTTON");
    PyRun_SimpleString("__builtins__.KEY_CANCEL = Core.KEY_CANCEL");
    PyRun_SimpleString("__builtins__.KEY_RBUTTON = Core.KEY_RBUTTON");
    PyRun_SimpleString("__builtins__.KEY_LBUTTON = Core.KEY_LBUTTON");
    PyRun_SimpleString("__builtins__.KEY_START = Core.KEY_START");
    PyRun_SimpleString("__builtins__.KEY_DELETE = Core.KEY_DELETE");
    PyRun_SimpleString("__builtins__.KEY_SPACE = Core.KEY_SPACE");
    PyRun_SimpleString("__builtins__.KEY_ESCAPE = Core.KEY_ESCAPE");
    PyRun_SimpleString("__builtins__.KEY_RETURN = Core.KEY_RETURN");
    PyRun_SimpleString("__builtins__.KEY_ENTER = Core.KEY_ENTER");
    PyRun_SimpleString("__builtins__.KEY_TAB = Core.KEY_TAB");
    PyRun_SimpleString("__builtins__.BUTTON_RIGHT = Core.BUTTON_RIGHT");
    PyRun_SimpleString("__builtins__.KEY_BACKSPACE = Core.KEY_BACKSPACE");
    PyRun_SimpleString("__builtins__.BUTTON_MIDDLE = Core.BUTTON_MIDDLE");
    PyRun_SimpleString("__builtins__.BUTTON_LEFT = Core.BUTTON_LEFT");
    PyRun_SimpleString("__builtins__.ANY = Core.ANY");
    PyRun_SimpleString("__builtins__.RELEASE = Core.RELEASE");
    PyRun_SimpleString("__builtins__.CLICK = Core.CLICK");
    PyRun_SimpleString("__builtins__.PRESS = Core.PRESS");
    PyRun_SimpleString("__builtins__.MOUSE = Core.MOUSE");
    PyRun_SimpleString("__builtins__.KEYBOARD = Core.KEYBOARD");
    PyRun_SimpleString("__builtins__.BUTTON_STATE_DOWN = Core.BUTTON_STATE_DOWN");
    PyRun_SimpleString("__builtins__.BUTTON_STATE_UP = Core.BUTTON_STATE_UP");
    PyRun_SimpleString("__builtins__.KEY_STATE_DOWN = Core.KEY_STATE_DOWN");
    PyRun_SimpleString("__builtins__.KEY_STATE_UP = Core.KEY_STATE_UP");

    
    // Make opengl methods available in the global namespace
    PyRun_SimpleString("__builtins__.GL_POINTS = OpenGL.GL_POINTS");
    PyRun_SimpleString("__builtins__.GL_LINES = OpenGL.GL_LINES"); 
    PyRun_SimpleString("__builtins__.GL_LINE_LOOP = OpenGL.GL_LINE_LOOP");
    PyRun_SimpleString("__builtins__.GL_LINE_STRIP = OpenGL.GL_LINE_STRIP");                           
    PyRun_SimpleString("__builtins__.GL_TRIANGLES = OpenGL.GL_TRIANGLES");                            
    PyRun_SimpleString("__builtins__.GL_TRIANGLE_STRIP = OpenGL.GL_TRIANGLE_STRIP");                       
    PyRun_SimpleString("__builtins__.GL_TRIANGLE_FAN = OpenGL.GL_TRIANGLE_FAN");                         
    PyRun_SimpleString("__builtins__.GL_QUADS = OpenGL.GL_QUADS");                                
    PyRun_SimpleString("__builtins__.GL_QUAD_STRIP = OpenGL.GL_QUAD_STRIP");
    PyRun_SimpleString("__builtins__.GL_POLYGON = OpenGL.GL_POLYGON");
    
    PyRun_SimpleString("__builtins__.glBegin = OpenGL.glBegin");
    PyRun_SimpleString("__builtins__.glEnd = OpenGL.glEnd");
    PyRun_SimpleString("__builtins__.glVertex = OpenGL.glVertex");
    PyRun_SimpleString("__builtins__.glNormal = OpenGL.glNormal");
    PyRun_SimpleString("__builtins__.glColor = OpenGL.glColor");
    PyRun_SimpleString("__builtins__.glTranslate = OpenGL.glTranslate");
    PyRun_SimpleString("__builtins__.glRotate = OpenGL.glRotate");
    PyRun_SimpleString("__builtins__.glScale = OpenGL.glScale");
    PyRun_SimpleString("__builtins__.glScale = OpenGL.glScale");
    PyRun_SimpleString("__builtins__.glPushMatrix = OpenGL.glPushMatrix");
    PyRun_SimpleString("__builtins__.glPopMatrix = OpenGL.glPopMatrix");


    // Create global engine instance
    mpy_PyEngine *py_global_engine = mpy_PyEngine_NEW();
    //py_global_engine->internalObject = (PyEngine *)Mango::Engine; // WARNING: this downcasting from a CoreEngine to a PyEngine is dangerous, and only works if you are SURE that Mango::Engine is actually a PyEngine!
    py_global_engine->internalObject = Mango::Engine; // WARNING: this downcasting from a CoreEngine to a PyEngine is dangerous, and only works if you are SURE that Mango::Engine is actually a PyEngine!
    PyModule_AddObject(module_core, "Engine", reinterpret_cast<PyObject *>(py_global_engine));
    PyRun_SimpleString("__builtins__.Engine = Core.Engine");
    
    // Create global keyboard instance
    mpy_CoreKeyboard *py_global_keyboard = mpy_CoreKeyboard_NEW();
    py_global_keyboard->internalObject = Mango::Keyboard;
    PyModule_AddObject(module_core, "Keyboard", reinterpret_cast<PyObject *>(py_global_keyboard));
    PyRun_SimpleString("__builtins__.Keyboard = Core.Keyboard");
    
    // Create global mouse instance
    mpy_CoreMouse *py_global_mouse = mpy_CoreMouse_NEW();
    py_global_mouse->internalObject = Mango::Mouse;
    PyModule_AddObject(module_core, "Mouse", reinterpret_cast<PyObject *>(py_global_mouse));
    PyRun_SimpleString("__builtins__.Mouse = Core.Mouse");

    // Create global frame instance
    PyGlobalFrame  = mpy_Frame_NEW();
    PyGlobalFrame->internalObject = Mango::GlobalFrame;
    PyGlobalFrame->parentFrame = NULL;
    Py_INCREF(PyGlobalFrame);
    PyModule_AddObject(module_core, "GlobalFrame", reinterpret_cast<PyObject *>(PyGlobalFrame));
    PyRun_SimpleString("__builtins__.GlobalFrame = Core.GlobalFrame");
    
    // Create global camera instance
    if (Mango::Camera != NULL){
      mpy_Frame *py_camera_focus = mpy_Frame_NEW();
      py_camera_focus->internalObject = Mango::Camera->parentFrame();      
      mpy_Frame_init(py_camera_focus, NULL, NULL);

      mpy_CoreCamera *py_global_camera = mpy_CoreCamera_NEW();
      Py_INCREF(py_camera_focus);
      py_global_camera->parentFrame = py_camera_focus;
      mpy_Object_init((mpy_Object *)py_global_camera, NULL, NULL);            
      
      py_global_camera->internalObject = Mango::Camera;
      PyModule_AddObject(module_core, "Camera", reinterpret_cast<PyObject *>(py_global_camera));
      PyRun_SimpleString("__builtins__.Camera = Core.Camera");
    }
  
    // Create global view instance
    if (Mango::View != NULL){
      mpy_CoreCamera *py_global_view = mpy_CoreCamera_NEW();
      py_global_view->internalObject = Mango::View;
      PyModule_AddObject(module_core, "View", reinterpret_cast<PyObject *>(py_global_view));
      PyRun_SimpleString("__builtins__.View = Core.View");
    }

    // Make environment available to extensions
    PyModule_AddObject(module_mpygen, "GLOBAL_FRAME", PyCapsule_New((void *)Mango::GlobalFrame, NULL, mpy_trivialDelMethod));
    PyModule_AddObject(module_mpygen, "PY_GLOBAL_FRAME", PyCapsule_New((void *)PyGlobalFrame, NULL, mpy_trivialDelMethod));
    PyModule_AddObject(module_mpygen, "ENGINE", PyCapsule_New((void *)Mango::Engine, NULL, mpy_trivialDelMethod));
    PyModule_AddObject(module_mpygen, "CAMERA", PyCapsule_New((void *)Mango::Camera, NULL, mpy_trivialDelMethod));
    PyModule_AddObject(module_mpygen, "VIEW", PyCapsule_New((void *)Mango::View, NULL, mpy_trivialDelMethod));
    PyModule_AddObject(module_mpygen, "KEYBOARD", PyCapsule_New((void *)Mango::Keyboard, NULL, mpy_trivialDelMethod));
    PyModule_AddObject(module_mpygen, "MOUSE", PyCapsule_New((void *)Mango::Mouse, NULL, mpy_trivialDelMethod));    

    //PyModule_AddObject(module_mpygen, "TYPE_OBJECT", PyCObject_FromVoidPtr((void *)&mpy_ObjectType, mpy_trivialDelMethod));

    PyObject *global_types = PyDict_New();
    PyModule_AddObject(module_mpygen, "TYPES", global_types);

    //PyDict_SetItemString(global_types, "mangopy.core.object", PyCObject_FromVoidPtr((void *)&mpy_ObjectType, mpy_trivialDelMethod));
    MangoPy::register_py_type_object("mangopy.core.input_event", &mpy_InputEventType);
    MangoPy::register_py_type_object("mangopy.core.vector", &mpy_VectorType);
    MangoPy::register_py_type_object("mangopy.core.matrix", &mpy_MatrixType);
    MangoPy::register_py_type_object("mangopy.core.object", &mpy_ObjectType);
    MangoPy::register_py_type_object("mangopy.core.frame", &mpy_FrameType);
    MangoPy::register_py_type_object("mangopy.core.py_engine", &mpy_PyEngineType);
    MangoPy::register_py_type_object("mangopy.core.core_camera", &mpy_CoreCameraType);
    MangoPy::register_py_type_object("mangopy.core.core_keyboard", &mpy_CoreKeyboardType);
    MangoPy::register_py_type_object("mangopy.core.core_mouse", &mpy_CoreMouseType);
    MangoPy::register_py_type_object("mangopy.core.triangle", &mpy_TriangleType);

    // Setup Python error buffer
    PyRun_SimpleString("\n\
#import sys \n\
class MangoPy_StdErr: \n\
    def write(self, msg): \n\
        _mpygen.writeToPythonScriptStderr(msg) \n\
sys.stderr = MangoPy_StdErr() \n\
");    

    // Setup Paths Array
    PyRun_SimpleString("Core.SOURCES = []");    
  }
示例#13
0
void renios_extend_inittab(void) {
    PyImport_AppendInittab("_renpy", init_renpy);
    PyImport_AppendInittab("pysdlsound.sound", initsound);
    PyImport_AppendInittab("pyobjus.pyobjus", initpyobjus);
    PyImport_AppendInittab("pygame_sdl2.font", initfont);
    PyImport_AppendInittab("pygame_sdl2.display", initdisplay);
    PyImport_AppendInittab("pygame_sdl2.mouse", initmouse);
    PyImport_AppendInittab("pygame_sdl2.key", initkey);
    PyImport_AppendInittab("pygame_sdl2.scrap", initscrap);
    PyImport_AppendInittab("pygame_sdl2.transform", inittransform);
    PyImport_AppendInittab("pygame_sdl2.draw", initdraw);
    PyImport_AppendInittab("pygame_sdl2.controller", initcontroller);
    PyImport_AppendInittab("pygame_sdl2.color", initcolor);
    PyImport_AppendInittab("pygame_sdl2.surface", initsurface);
    PyImport_AppendInittab("pygame_sdl2.rect", initrect);
    PyImport_AppendInittab("pygame_sdl2.joystick", initjoystick);
    PyImport_AppendInittab("pygame_sdl2.image", initimage);
    PyImport_AppendInittab("pygame_sdl2.gfxdraw", initgfxdraw);
    PyImport_AppendInittab("pygame_sdl2.locals", initlocals);
    PyImport_AppendInittab("pygame_sdl2.rwobject", initrwobject);
    PyImport_AppendInittab("pygame_sdl2.error", initerror);
    PyImport_AppendInittab("pygame_sdl2.pygame_time", initpygame_time);
    PyImport_AppendInittab("pygame_sdl2.render", initrender);
    PyImport_AppendInittab("pygame_sdl2.event", initevent);
    PyImport_AppendInittab("renpy.style", initstyle);
    PyImport_AppendInittab("renpy.gl.gldraw", initgldraw);
    PyImport_AppendInittab("renpy.gl.glenviron_shader", initglenviron_shader);
    PyImport_AppendInittab("renpy.gl.gl", initgl);
    PyImport_AppendInittab("renpy.gl.glrtt_fbo", initglrtt_fbo);
    PyImport_AppendInittab("renpy.gl.gltexture", initgltexture);
    PyImport_AppendInittab("renpy.gl.glrtt_copy", initglrtt_copy);
    PyImport_AppendInittab("renpy.display.accelerator", initaccelerator);
    PyImport_AppendInittab("renpy.display.render", initrender);
    PyImport_AppendInittab("renpy.styledata.stylesets", initstylesets);
    PyImport_AppendInittab("renpy.styledata.style_insensitive_functions", initstyle_insensitive_functions);
    PyImport_AppendInittab("renpy.styledata.style_functions", initstyle_functions);
    PyImport_AppendInittab("renpy.styledata.style_activate_functions", initstyle_activate_functions);
    PyImport_AppendInittab("renpy.styledata.style_selected_hover_functions", initstyle_selected_hover_functions);
    PyImport_AppendInittab("renpy.styledata.style_hover_functions", initstyle_hover_functions);
    PyImport_AppendInittab("renpy.styledata.style_selected_idle_functions", initstyle_selected_idle_functions);
    PyImport_AppendInittab("renpy.styledata.style_selected_functions", initstyle_selected_functions);
    PyImport_AppendInittab("renpy.styledata.styleclass", initstyleclass);
    PyImport_AppendInittab("renpy.styledata.style_selected_insensitive_functions", initstyle_selected_insensitive_functions);
    PyImport_AppendInittab("renpy.styledata.style_idle_functions", initstyle_idle_functions);
    PyImport_AppendInittab("renpy.styledata.style_selected_activate_functions", initstyle_selected_activate_functions);
    PyImport_AppendInittab("renpy.text.ftfont", initftfont);
    PyImport_AppendInittab("renpy.text.texwrap", inittexwrap);
    PyImport_AppendInittab("renpy.text.textsupport", inittextsupport);
}
示例#14
0
void init_uwsgi_embedded_module() {
	PyObject *new_uwsgi_module, *zero;
	int i;

	PyType_Ready(&uwsgi_InputType);

	/* initialize for stats */
	up.workers_tuple = PyTuple_New(uwsgi.numproc);
	for (i = 0; i < uwsgi.numproc; i++) {
		zero = PyDict_New();
		Py_INCREF(zero);
		PyTuple_SetItem(up.workers_tuple, i, zero);
	}


#ifdef PYTHREE
	PyImport_AppendInittab("uwsgi", init_uwsgi3);
	new_uwsgi_module = PyImport_AddModule("uwsgi");
#else
	new_uwsgi_module = Py_InitModule3("uwsgi", NULL, uwsgi_py_doc);
#endif
	if (new_uwsgi_module == NULL) {
		uwsgi_log("could not initialize the uwsgi python module\n");
		exit(1);
	}



	Py_INCREF((PyObject *) &uwsgi_InputType);

	up.embedded_dict = PyModule_GetDict(new_uwsgi_module);
	if (!up.embedded_dict) {
		uwsgi_log("could not get uwsgi module __dict__\n");
		exit(1);
	}

	// just for safety
	Py_INCREF(up.embedded_dict);


	if (PyDict_SetItemString(up.embedded_dict, "version", PyString_FromString(UWSGI_VERSION))) {
		PyErr_Print();
		exit(1);
	}

	PyObject *uwsgi_py_version_info = PyTuple_New(5);

	PyTuple_SetItem(uwsgi_py_version_info, 0, PyInt_FromLong(UWSGI_VERSION_BASE));
	PyTuple_SetItem(uwsgi_py_version_info, 1, PyInt_FromLong(UWSGI_VERSION_MAJOR));
	PyTuple_SetItem(uwsgi_py_version_info, 2, PyInt_FromLong(UWSGI_VERSION_MINOR));
	PyTuple_SetItem(uwsgi_py_version_info, 3, PyInt_FromLong(UWSGI_VERSION_REVISION));
	PyTuple_SetItem(uwsgi_py_version_info, 4, PyString_FromString(UWSGI_VERSION_CUSTOM));

	if (PyDict_SetItemString(up.embedded_dict, "version_info", uwsgi_py_version_info)) {
		PyErr_Print();
		exit(1);
	}



	if (PyDict_SetItemString(up.embedded_dict, "hostname", PyString_FromStringAndSize(uwsgi.hostname, uwsgi.hostname_len))) {
		PyErr_Print();
		exit(1);
	}

	if (uwsgi.mode) {
		if (PyDict_SetItemString(up.embedded_dict, "mode", PyString_FromString(uwsgi.mode))) {
			PyErr_Print();
			exit(1);
		}
	}

	if (uwsgi.pidfile) {
		if (PyDict_SetItemString(up.embedded_dict, "pidfile", PyString_FromString(uwsgi.pidfile))) {
			PyErr_Print();
			exit(1);
		}
	}

#ifdef UWSGI_SPOOLER
	if (uwsgi.spoolers) {
		int sc = 0;
		struct uwsgi_spooler *uspool = uwsgi.spoolers;
		while(uspool) { sc++; uspool = uspool->next;}

		PyObject *py_spooler_tuple = PyTuple_New(sc);

		uspool = uwsgi.spoolers;
		sc = 0;

		while(uspool) {
			PyTuple_SetItem(py_spooler_tuple, sc, PyString_FromString(uspool->dir));
			sc++;
			uspool = uspool->next;
		}

		if (PyDict_SetItemString(up.embedded_dict, "spoolers", py_spooler_tuple)) {
                	PyErr_Print();
                	exit(1);
        	}
	}
#endif



	if (PyDict_SetItemString(up.embedded_dict, "SPOOL_RETRY", PyInt_FromLong(-1))) {
		PyErr_Print();
		exit(1);
	}

	if (PyDict_SetItemString(up.embedded_dict, "SPOOL_OK", PyInt_FromLong(-2))) {
		PyErr_Print();
		exit(1);
	}

	if (PyDict_SetItemString(up.embedded_dict, "SPOOL_IGNORE", PyInt_FromLong(0))) {
		PyErr_Print();
		exit(1);
	}

	if (PyDict_SetItemString(up.embedded_dict, "numproc", PyInt_FromLong(uwsgi.numproc))) {
		PyErr_Print();
		exit(1);
	}

	if (PyDict_SetItemString(up.embedded_dict, "has_threads", PyInt_FromLong(uwsgi.has_threads))) {
		PyErr_Print();
		exit(1);
	}

	if (PyDict_SetItemString(up.embedded_dict, "cores", PyInt_FromLong(uwsgi.cores))) {
		PyErr_Print();
		exit(1);
	}

	if (uwsgi.loop) {
		if (PyDict_SetItemString(up.embedded_dict, "loop", PyString_FromString(uwsgi.loop))) {
			PyErr_Print();
			exit(1);
		}
	}
	else {
		PyDict_SetItemString(up.embedded_dict, "loop", Py_None);
	}

	PyObject *py_opt_dict = PyDict_New();
	for (i = 0; i < uwsgi.exported_opts_cnt; i++) {
		if (PyDict_Contains(py_opt_dict, PyString_FromString(uwsgi.exported_opts[i]->key))) {
			PyObject *py_opt_item = PyDict_GetItemString(py_opt_dict, uwsgi.exported_opts[i]->key);
			if (PyList_Check(py_opt_item)) {
				if (uwsgi.exported_opts[i]->value == NULL) {
					PyList_Append(py_opt_item, Py_True);
				}
				else {
					PyList_Append(py_opt_item, PyString_FromString(uwsgi.exported_opts[i]->value));
				}
			}
			else {
				PyObject *py_opt_list = PyList_New(0);
				PyList_Append(py_opt_list, py_opt_item);
				if (uwsgi.exported_opts[i]->value == NULL) {
					PyList_Append(py_opt_list, Py_True);
				}
				else {
					PyList_Append(py_opt_list, PyString_FromString(uwsgi.exported_opts[i]->value));
				}

				PyDict_SetItemString(py_opt_dict, uwsgi.exported_opts[i]->key, py_opt_list);
			}
		}
		else {
			if (uwsgi.exported_opts[i]->value == NULL) {
				PyDict_SetItemString(py_opt_dict, uwsgi.exported_opts[i]->key, Py_True);
			}
			else {
				PyDict_SetItemString(py_opt_dict, uwsgi.exported_opts[i]->key, PyString_FromString(uwsgi.exported_opts[i]->value));
			}
		}
	}

	if (PyDict_SetItemString(up.embedded_dict, "opt", py_opt_dict)) {
		PyErr_Print();
		exit(1);
	}

	PyObject *py_magic_table = PyDict_New();
	uint8_t mtk;
	for (i = 0; i <= 0xff; i++) {
		// a bit of magic :P
		mtk = i;
                if (uwsgi.magic_table[i]) {
			if (uwsgi.magic_table[i][0] != 0) {
				PyDict_SetItem(py_magic_table, PyString_FromStringAndSize((char *) &mtk, 1), PyString_FromString(uwsgi.magic_table[i]));
			}
		}
        }

	if (PyDict_SetItemString(up.embedded_dict, "magic_table", py_magic_table)) {
		PyErr_Print();
		exit(1);
	}

#ifdef UNBIT
	if (PyDict_SetItemString(up.embedded_dict, "unbit", Py_True)) {
#else
	if (PyDict_SetItemString(up.embedded_dict, "unbit", Py_None)) {
#endif
		PyErr_Print();
		exit(1);
	}

	if (PyDict_SetItemString(up.embedded_dict, "buffer_size", PyInt_FromLong(uwsgi.buffer_size))) {
		PyErr_Print();
		exit(1);
	}

	if (PyDict_SetItemString(up.embedded_dict, "started_on", PyInt_FromLong(uwsgi.start_tv.tv_sec))) {
		PyErr_Print();
		exit(1);
	}

	if (PyDict_SetItemString(up.embedded_dict, "start_response", up.wsgi_spitout)) {
		PyErr_Print();
		exit(1);
	}


	if (PyDict_SetItemString(up.embedded_dict, "applications", Py_None)) {
		PyErr_Print();
		exit(1);
	}

	if (uwsgi.is_a_reload) {
		if (PyDict_SetItemString(up.embedded_dict, "is_a_reload", Py_True)) {
			PyErr_Print();
			exit(1);
		}
	}
	else {
		if (PyDict_SetItemString(up.embedded_dict, "is_a_reload", Py_False)) {
			PyErr_Print();
			exit(1);
		}
	}

	up.embedded_args = PyTuple_New(2);
	if (!up.embedded_args) {
		PyErr_Print();
		exit(1);
	}

	if (PyDict_SetItemString(up.embedded_dict, "message_manager_marshal", Py_None)) {
		PyErr_Print();
		exit(1);
	}

	init_uwsgi_module_advanced(new_uwsgi_module);

#ifdef UWSGI_SPOOLER
	if (uwsgi.spoolers) {
		init_uwsgi_module_spooler(new_uwsgi_module);
	}
#endif


	if (uwsgi.sharedareasize > 0 && uwsgi.sharedarea) {
		init_uwsgi_module_sharedarea(new_uwsgi_module);
	}

	if (uwsgi.cache_max_items > 0) {
		init_uwsgi_module_cache(new_uwsgi_module);
	}

	if (uwsgi.queue_size > 0) {
		init_uwsgi_module_queue(new_uwsgi_module);
	}

#ifdef UWSGI_SNMP
	if (uwsgi.snmp) {
		init_uwsgi_module_snmp(new_uwsgi_module);
	}
#endif

	if (up.extension) {
		up.extension();
	}
}
#endif



int uwsgi_python_magic(char *mountpoint, char *lazy) {

	char *qc = strchr(lazy, ':');
	if (qc) {
		qc[0] = 0;
		up.callable = qc + 1;
	}

	if (!strcmp(lazy + strlen(lazy) - 3, ".py")) {
		up.file_config = lazy;
		return 1;
	}
	else if (!strcmp(lazy + strlen(lazy) - 5, ".wsgi")) {
		up.file_config = lazy;
		return 1;
	}
	else if (qc && strchr(lazy, '.')) {
		up.wsgi_config = lazy;
		return 1;
	}

	// reset lazy
	if (qc) {
		qc[0] = ':';
	}
	return 0;

}
示例#15
0
__attribute__((constructor)) void append_metalmem()
{
    PyImport_AppendInittab("_metalmem", init_metalmem);
}
示例#16
0
static int
Python3_Init(void)
{
	if (!py3initialised) {
#ifdef DYNAMIC_PYTHON3
		if (!python3_enabled(TRUE)) {
			EMSG(_("E263: Sorry, this command is disabled, the Python library could not be loaded."));
			goto fail;
		}
#endif

		init_structs();


#ifdef PYTHON3_HOME
		Py_SetPythonHome(PYTHON3_HOME);
#endif

		PyImport_AppendInittab("vim", Py3Init_vim);

#if !defined(MACOS) || defined(MACOS_X_UNIX)
		Py_Initialize();
#else
		PyMac_Initialize();
#endif
		/* Initialise threads, and below save the state using
		 * PyEval_SaveThread.  Without the call to PyEval_SaveThread, thread
		 * specific state (such as the system trace hook), will be lost
		 * between invocations of Python code. */
		PyEval_InitThreads();
#ifdef DYNAMIC_PYTHON3
		get_py3_exceptions();
#endif

		if (PythonIO_Init_io())
			goto fail;

		globals = PyModule_GetDict(PyImport_AddModule("__main__"));

		/* Remove the element from sys.path that was added because of our
		 * argv[0] value in Py3Init_vim().  Previously we used an empty
		 * string, but depending on the OS we then get an empty entry or
		 * the current directory in sys.path.
		 * Only after vim has been imported, the element does exist in
		 * sys.path.
		 */
		PyRun_SimpleString("import vim; import sys; sys.path = list(filter(lambda x: not x.endswith('must>not&exist'), sys.path))");

		/* lock is created and acquired in PyEval_InitThreads() and thread
		 * state is created in Py_Initialize()
		 * there _PyGILState_NoteThreadState() also sets gilcounter to 1
		 * (python must have threads enabled!)
		 * so the following does both: unlock GIL and save thread state in TLS
		 * without deleting thread state
		 */
		PyEval_SaveThread();

		py3initialised = 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_io() has not completed successfully (it will
	 * not do anything in this case).
	 */
	PythonIO_Flush();
	return -1;
}
示例#17
0
int init_with_instance(HMODULE hmod_exe, char *frozen)
{

	int rc = 0;
	HMODULE hmod_pydll;

/*	Py_NoSiteFlag = 1; /* Suppress 'import site' */
/*	Py_InspectFlag = 1; /* Needed to determine whether to exit at SystemExit */

	calc_dirname(hmod_exe);
//	wprintf(L"modulename %s\n", modulename);
//	wprintf(L"dirname %s\n", dirname);

	if (!locate_script(hmod_exe)) {
		SystemError(-1, "FATAL ERROR: Could not locate script");
//		printf("FATAL ERROR locating script\n");
		return -1;
	}

	hmod_pydll = load_pythondll();
	if (hmod_pydll == NULL) {
		SystemError(-1, "FATAL ERROR: Could not load python library");
//		printf("FATAL Error: could not load python library\n");
		return -1;
	}
	if (PythonLoaded(hmod_pydll) < 0) {
		SystemError(-1, "FATAL ERROR: Failed to load some Python symbols");
//		printf("FATAL Error: failed to load some Python symbols\n");
		return -1;
	}

	set_vars(hmod_pydll);

	/*
	  _memimporter contains the magic which allows to load
	  dlls from memory, without unpacking them to the file-system.

	  It is compiled into all the exe-stubs.
	*/
	PyImport_AppendInittab("_memimporter", PyInit__memimporter);

	/*
	  Start the ball rolling.
	*/
	Py_SetProgramName(modulename);
	Py_SetPath(libfilename);
	Py_Initialize();


	/* Set sys.frozen so apps that care can tell.  If the caller did pass
	   NULL, sys.frozen will be set to 'True'.  If a string is passed this
	   is used as the frozen attribute.  run.c passes "console_exe",
	   run_w.c passes "windows_exe", run_dll.c passes "dll" This falls
	   apart when you consider that in some cases, a single process may
	   end up with two py2exe generated apps - but still, we reset frozen
	   to the correct 'current' value for the newly initializing app.
	*/
	if (frozen == NULL)
		PySys_SetObject("frozen", PyBool_FromLong(1));
	else {
		PyObject *o = PyUnicode_FromString(frozen);
		if (o) {
			PySys_SetObject("frozen", o);
			Py_DECREF(o);
		}
	}
	return rc;
}
示例#18
0
int
plugin_init (struct plugin_name_args *plugin_info,
             struct plugin_gcc_version *version)
{
    LOG("plugin_init started");

    if (!plugin_default_version_check (version, &gcc_version)) {
        return 1;
    }

#if PY_MAJOR_VERSION >= 3
    /*
      Python 3 added internal buffering to sys.stdout and sys.stderr, but this
      leads to unpredictable interleavings of messages from gcc, such as from calling
      gcc.warning() vs those from python scripts, such as from print() and
      sys.stdout.write()

      Suppress the buffering, to better support mixed gcc/python output:
    */
    Py_UnbufferedStdioFlag = 1;
#endif

    PyImport_AppendInittab("gcc", PyInit_gcc);

    LOG("calling Py_Initialize...");

    Py_Initialize();

    LOG("Py_Initialize finished");

    gcc_python_globals.module = PyImport_ImportModule("gcc");

    PyEval_InitThreads();
  
    if (!gcc_python_init_gcc_module(plugin_info)) {
        return 1;
    }

    if (!setup_sys(plugin_info)) {
        return 1;
    }

    /* Init other modules */
    gcc_python_wrapper_init();

    /* FIXME: properly integrate them within the module hierarchy */

    gcc_python_version_init(version);

    autogenerated_callgraph_init_types();  /* FIXME: error checking! */
    autogenerated_cfg_init_types();  /* FIXME: error checking! */
    autogenerated_function_init_types();  /* FIXME: error checking! */
    autogenerated_gimple_init_types();  /* FIXME: error checking! */
    autogenerated_location_init_types();  /* FIXME: error checking! */
    autogenerated_option_init_types();  /* FIXME: error checking! */
    autogenerated_parameter_init_types();  /* FIXME: error checking! */
    autogenerated_pass_init_types();  /* FIXME: error checking! */
    autogenerated_pretty_printer_init_types();  /* FIXME: error checking! */
    autogenerated_rtl_init_types(); /* FIXME: error checking! */
    autogenerated_tree_init_types(); /* FIXME: error checking! */
    autogenerated_variable_init_types(); /* FIXME: error checking! */



    autogenerated_callgraph_add_types(gcc_python_globals.module);
    autogenerated_cfg_add_types(gcc_python_globals.module);
    autogenerated_function_add_types(gcc_python_globals.module);
    autogenerated_gimple_add_types(gcc_python_globals.module);
    autogenerated_location_add_types(gcc_python_globals.module);
    autogenerated_option_add_types(gcc_python_globals.module);
    autogenerated_parameter_add_types(gcc_python_globals.module);
    autogenerated_pass_add_types(gcc_python_globals.module);
    autogenerated_pretty_printer_add_types(gcc_python_globals.module);
    autogenerated_rtl_add_types(gcc_python_globals.module);
    autogenerated_tree_add_types(gcc_python_globals.module);
    autogenerated_variable_add_types(gcc_python_globals.module);


    /* Register at-exit finalization for the plugin: */
    register_callback(plugin_info->base_name, PLUGIN_FINISH,
                      on_plugin_finish, NULL);

    gcc_python_run_any_command();
    gcc_python_run_any_script();

    //printf("%s:%i:got here\n", __FILE__, __LINE__);

#if GCC_PYTHON_TRACE_ALL_EVENTS
#define DEFEVENT(NAME) \
    if (NAME != PLUGIN_PASS_MANAGER_SETUP &&         \
        NAME != PLUGIN_INFO &&                       \
	NAME != PLUGIN_REGISTER_GGC_ROOTS &&         \
	NAME != PLUGIN_REGISTER_GGC_CACHES) {        \
    register_callback(plugin_info->base_name, NAME,  \
		      trace_callback_for_##NAME, NULL); \
    }
# include "plugin.def"
# undef DEFEVENT
#endif /* GCC_PYTHON_TRACE_ALL_EVENTS */

    LOG("init_plugin finished");

    return 0;
}
示例#19
0
void PythonContext::GlobalInit()
{
  // must happen on the UI thread
  if(qApp->thread() != QThread::currentThread())
  {
    qFatal("PythonContext::GlobalInit MUST be called from the UI thread");
    return;
  }

  // for the exception signal
  qRegisterMetaType<QList<QString>>("QList<QString>");

  PyImport_AppendInittab("_renderdoc", &PyInit_renderdoc);
  PyImport_AppendInittab("_qrenderdoc", &PyInit_qrenderdoc);

#if defined(STATIC_QRENDERDOC)
  // add the location where our libs will be for statically-linked python installs
  {
    QDir bin = QFileInfo(QCoreApplication::applicationFilePath()).absoluteDir();

    QString pylibs = QDir::cleanPath(bin.absoluteFilePath(lit("../share/renderdoc/pylibs")));

    pylibs.toWCharArray(python_home);

    Py_SetPythonHome(python_home);
  }
#endif

  Py_SetProgramName(program_name);

  Py_Initialize();

  PyEval_InitThreads();

  OutputRedirectorType.tp_name = "renderdoc_output_redirector";
  OutputRedirectorType.tp_basicsize = sizeof(OutputRedirector);
  OutputRedirectorType.tp_flags = Py_TPFLAGS_DEFAULT;
  OutputRedirectorType.tp_doc =
      "Output redirector, to be able to catch output to stdout and stderr";
  OutputRedirectorType.tp_new = PyType_GenericNew;
  OutputRedirectorType.tp_dealloc = &PythonContext::outstream_del;
  OutputRedirectorType.tp_methods = OutputRedirector_methods;

  OutputRedirector_methods[0].ml_meth = &PythonContext::outstream_write;
  OutputRedirector_methods[1].ml_meth = &PythonContext::outstream_flush;

  PyObject *main_module = PyImport_AddModule("__main__");

  PyModule_AddObject(main_module, "renderdoc", PyImport_ImportModule("_renderdoc"));
  PyModule_AddObject(main_module, "qrenderdoc", PyImport_ImportModule("_qrenderdoc"));

  main_dict = PyModule_GetDict(main_module);

  // replace sys.stdout and sys.stderr with our own objects. These have a 'this' pointer of NULL,
  // which then indicates they need to forward to a global object

  // import sys
  PyDict_SetItemString(main_dict, "sys", PyImport_ImportModule("sys"));

  PyObject *rlcompleter = PyImport_ImportModule("rlcompleter");

  if(rlcompleter)
  {
    PyDict_SetItemString(main_dict, "rlcompleter", rlcompleter);
  }
  else
  {
    // ignore a failed import
    PyErr_Clear();
  }

  // sysobj = sys
  PyObject *sysobj = PyDict_GetItemString(main_dict, "sys");

  // sysobj.stdout = renderdoc_output_redirector()
  // sysobj.stderr = renderdoc_output_redirector()
  if(PyType_Ready(&OutputRedirectorType) >= 0)
  {
    // for compatibility with earlier versions of python that took a char * instead of const char *
    char noparams[1] = "";

    PyObject *redirector = PyObject_CallFunction((PyObject *)&OutputRedirectorType, noparams);
    PyObject_SetAttrString(sysobj, "stdout", redirector);

    OutputRedirector *output = (OutputRedirector *)redirector;
    output->isStdError = 0;
    output->context = NULL;

    redirector = PyObject_CallFunction((PyObject *)&OutputRedirectorType, noparams);
    PyObject_SetAttrString(sysobj, "stderr", redirector);

    output = (OutputRedirector *)redirector;
    output->isStdError = 1;
    output->context = NULL;
  }

// if we need to append to sys.path to locate PySide2, do that now
#if defined(PYSIDE2_SYS_PATH)
  {
    PyObject *syspath = PyObject_GetAttrString(sysobj, "path");

#ifndef STRINGIZE
#define STRINGIZE2(a) #a
#define STRINGIZE(a) STRINGIZE2(a)
#endif

    PyObject *str = PyUnicode_FromString(STRINGIZE(PYSIDE2_SYS_PATH));

    PyList_Append(syspath, str);

    Py_DecRef(str);
    Py_DecRef(syspath);
  }
#endif

// set up PySide
#if PYSIDE2_ENABLED
  {
    Shiboken::AutoDecRef core(Shiboken::Module::import("PySide2.QtCore"));
    if(!core.isNull())
      SbkPySide2_QtCoreTypes = Shiboken::Module::getTypes(core);
    else
      qCritical() << "Failed to load PySide2.QtCore";

    Shiboken::AutoDecRef gui(Shiboken::Module::import("PySide2.QtGui"));
    if(!gui.isNull())
      SbkPySide2_QtGuiTypes = Shiboken::Module::getTypes(gui);
    else
      qCritical() << "Failed to load PySide2.QtGui";

    Shiboken::AutoDecRef widgets(Shiboken::Module::import("PySide2.QtWidgets"));
    if(!widgets.isNull())
      SbkPySide2_QtWidgetsTypes = Shiboken::Module::getTypes(widgets);
    else
      qCritical() << "Failed to load PySide2.QtWidgets";
  }
#endif

  // release GIL so that python work can now happen on any thread
  PyEval_SaveThread();
}