当前位置: 首页>>代码示例>>C++>>正文


C++ PyImport_AddModule函数代码示例

本文整理汇总了C++中PyImport_AddModule函数的典型用法代码示例。如果您正苦于以下问题:C++ PyImport_AddModule函数的具体用法?C++ PyImport_AddModule怎么用?C++ PyImport_AddModule使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了PyImport_AddModule函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。

示例1: weechat_python_exec

void *
weechat_python_exec (struct t_plugin_script *script,
                     int ret_type, const char *function,
                     char *format, void **argv)
{
    struct t_plugin_script *old_python_current_script;
    PyThreadState *old_interpreter;
    PyObject *evMain, *evDict, *evFunc, *rc;
    void *argv2[16], *ret_value;
    int i, argc, *ret_int;

    /* PyEval_AcquireLock (); */

    old_python_current_script = python_current_script;
    old_interpreter = NULL;
    if (script->interpreter)
    {
        old_interpreter = PyThreadState_Swap (NULL);
        PyThreadState_Swap (script->interpreter);
    }

    evMain = PyImport_AddModule ((char *) "__main__");
    evDict = PyModule_GetDict (evMain);
    evFunc = PyDict_GetItemString (evDict, function);

    if ( !(evFunc && PyCallable_Check (evFunc)) )
    {
        weechat_printf (NULL,
                        weechat_gettext ("%s%s: unable to run function \"%s\""),
                        weechat_prefix ("error"), PYTHON_PLUGIN_NAME, function);
        /* PyEval_ReleaseThread (python_current_script->interpreter); */
        if (old_interpreter)
            PyThreadState_Swap (old_interpreter);
        return NULL;
    }

    python_current_script = script;

    if (argv && argv[0])
    {
        argc = strlen (format);
        for (i = 0; i < 16; i++)
        {
            argv2[i] = (i < argc) ? argv[i] : NULL;
        }
        rc = PyObject_CallFunction (evFunc, format,
                                    argv2[0], argv2[1],
                                    argv2[2], argv2[3],
                                    argv2[4], argv2[5],
                                    argv2[6], argv2[7],
                                    argv2[8], argv2[9],
                                    argv2[10], argv2[11],
                                    argv2[12], argv2[13],
                                    argv2[14], argv2[15]);
    }
    else
    {
        rc = PyObject_CallFunction (evFunc, NULL);
    }

    ret_value = NULL;

    /*
     * ugly hack : rc = NULL while 'return weechat.WEECHAT_RC_OK ....
     * because of '#define WEECHAT_RC_OK 0'
     */
    if (rc ==  NULL)
        rc = PyLong_FromLong ((long)0);

    if (PyErr_Occurred())
    {
        PyErr_Print ();
        Py_XDECREF(rc);
    }
    else if ((ret_type == WEECHAT_SCRIPT_EXEC_STRING) && (PyUnicode_Check (rc)))
    {
        ret_value = weechat_python_unicode_to_string (rc);
        Py_XDECREF(rc);
    }
    else if ((ret_type == WEECHAT_SCRIPT_EXEC_STRING) && (PyBytes_Check (rc)))
    {
        if (PyBytes_AsString (rc))
            ret_value = strdup (PyBytes_AsString (rc));
        else
            ret_value = NULL;
        Py_XDECREF(rc);
    }
    else if ((ret_type == WEECHAT_SCRIPT_EXEC_INT) && (PY_INTEGER_CHECK(rc)))
    {
        ret_int = malloc (sizeof (*ret_int));
        if (ret_int)
            *ret_int = (int) PyLong_AsLong (rc);
        ret_value = ret_int;
        Py_XDECREF(rc);
    }
    else if (ret_type == WEECHAT_SCRIPT_EXEC_HASHTABLE)
    {
        ret_value = weechat_python_dict_to_hashtable (rc,
                                                      WEECHAT_SCRIPT_HASHTABLE_DEFAULT_SIZE,
                                                      WEECHAT_HASHTABLE_STRING,
//.........这里部分代码省略.........
开发者ID:AlexTalker,项目名称:weechat,代码行数:101,代码来源:weechat-python.c

示例2: PyObject_HEAD_INIT


//.........这里部分代码省略.........
#else
PyMODINIT_FUNC PyInit__guide_builder(void); /*proto*/
PyMODINIT_FUNC PyInit__guide_builder(void)
#endif
{
  PyObject *__pyx_t_1 = NULL;
  __Pyx_RefNannyDeclarations
  #if CYTHON_REFNANNY
  __Pyx_RefNanny = __Pyx_RefNannyImportAPI("refnanny");
  if (!__Pyx_RefNanny) {
      PyErr_Clear();
      __Pyx_RefNanny = __Pyx_RefNannyImportAPI("Cython.Runtime.refnanny");
      if (!__Pyx_RefNanny)
          Py_FatalError("failed to import 'refnanny' module");
  }
  #endif
  __Pyx_RefNannySetupContext("PyMODINIT_FUNC PyInit__guide_builder(void)", 0);
  if ( __Pyx_check_binary_version() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
  __pyx_empty_tuple = PyTuple_New(0); if (unlikely(!__pyx_empty_tuple)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
  __pyx_empty_bytes = PyBytes_FromStringAndSize("", 0); if (unlikely(!__pyx_empty_bytes)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
  #ifdef __Pyx_CyFunction_USED
  if (__Pyx_CyFunction_init() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
  #endif
  #ifdef __Pyx_FusedFunction_USED
  if (__pyx_FusedFunction_init() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
  #endif
  #ifdef __Pyx_Generator_USED
  if (__pyx_Generator_init() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
  #endif
  /*--- Library function declarations ---*/
  /*--- Threads initialization code ---*/
  #if defined(__PYX_FORCE_INIT_THREADS) && __PYX_FORCE_INIT_THREADS
  #ifdef WITH_THREAD /* Python build with threading support? */
  PyEval_InitThreads();
  #endif
  #endif
  /*--- Module creation code ---*/
  #if PY_MAJOR_VERSION < 3
  __pyx_m = Py_InitModule4(__Pyx_NAMESTR("_guide_builder"), __pyx_methods, 0, 0, PYTHON_API_VERSION); Py_XINCREF(__pyx_m);
  #else
  __pyx_m = PyModule_Create(&__pyx_moduledef);
  #endif
  if (unlikely(!__pyx_m)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
  #if PY_MAJOR_VERSION >= 3
  {
    PyObject *modules = PyImport_GetModuleDict(); if (unlikely(!modules)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
    if (!PyDict_GetItemString(modules, "_guide_builder")) {
      if (unlikely(PyDict_SetItemString(modules, "_guide_builder", __pyx_m) < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
    }
  }
  #endif
  __pyx_b = PyImport_AddModule(__Pyx_NAMESTR(__Pyx_BUILTIN_MODULE_NAME)); if (unlikely(!__pyx_b)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
  #if CYTHON_COMPILING_IN_PYPY
  Py_INCREF(__pyx_b);
  #endif
  if (__Pyx_SetAttrString(__pyx_m, "__builtins__", __pyx_b) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;};
  /*--- Initialize various global constants etc. ---*/
  if (unlikely(__Pyx_InitGlobals() < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
  if (__pyx_module_is_main__guide_builder) {
    if (__Pyx_SetAttrString(__pyx_m, "__name__", __pyx_n_s____main__) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;};
  }
  /*--- Builtin init code ---*/
  if (unlikely(__Pyx_InitCachedBuiltins() < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
  /*--- Constants init code ---*/
  if (unlikely(__Pyx_InitCachedConstants() < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
  /*--- Global init code ---*/
  /*--- Variable export code ---*/
  /*--- Function export code ---*/
  /*--- Type init code ---*/
  /*--- Type import code ---*/
  /*--- Variable import code ---*/
  /*--- Function import code ---*/
  /*--- Execution code ---*/

  /* "_guide_builder.pxd":1
 * from _base_types cimport BaseType             # <<<<<<<<<<<<<<
 * from _dawg cimport Dawg
 * from _dictionary cimport Dictionary
 */
  __pyx_t_1 = PyDict_New(); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
  __Pyx_GOTREF(((PyObject *)__pyx_t_1));
  if (PyObject_SetAttr(__pyx_m, __pyx_n_s____test__, ((PyObject *)__pyx_t_1)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
  __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0;
  goto __pyx_L0;
  __pyx_L1_error:;
  __Pyx_XDECREF(__pyx_t_1);
  if (__pyx_m) {
    __Pyx_AddTraceback("init _guide_builder", __pyx_clineno, __pyx_lineno, __pyx_filename);
    Py_DECREF(__pyx_m); __pyx_m = 0;
  } else if (!PyErr_Occurred()) {
    PyErr_SetString(PyExc_ImportError, "init _guide_builder");
  }
  __pyx_L0:;
  __Pyx_RefNannyFinishContext();
  #if PY_MAJOR_VERSION < 3
  return;
  #else
  return __pyx_m;
  #endif
}
开发者ID:IMDagger,项目名称:DAWG,代码行数:101,代码来源:_guide_builder.cpp

示例3: __Pyx_XDECREF


//.........这里部分代码省略.........
PyMODINIT_FUNC initcython_struct(void)
#else
PyMODINIT_FUNC PyInit_cython_struct(void); /*proto*/
PyMODINIT_FUNC PyInit_cython_struct(void)
#endif
{
  PyObject *__pyx_t_1 = NULL;
  __Pyx_RefNannyDeclarations
  #if CYTHON_REFNANNY
  __Pyx_RefNanny = __Pyx_RefNannyImportAPI("refnanny");
  if (!__Pyx_RefNanny) {
      PyErr_Clear();
      __Pyx_RefNanny = __Pyx_RefNannyImportAPI("Cython.Runtime.refnanny");
      if (!__Pyx_RefNanny)
          Py_FatalError("failed to import 'refnanny' module");
  }
  #endif
  __Pyx_RefNannySetupContext("PyMODINIT_FUNC PyInit_cython_struct(void)");
  if ( __Pyx_check_binary_version() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
  __pyx_empty_tuple = PyTuple_New(0); if (unlikely(!__pyx_empty_tuple)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
  __pyx_empty_bytes = PyBytes_FromStringAndSize("", 0); if (unlikely(!__pyx_empty_bytes)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
  #ifdef __pyx_binding_PyCFunctionType_USED
  if (__pyx_binding_PyCFunctionType_init() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
  #endif
  /*--- Library function declarations ---*/
  /*--- Threads initialization code ---*/
  #if defined(__PYX_FORCE_INIT_THREADS) && __PYX_FORCE_INIT_THREADS
  #ifdef WITH_THREAD /* Python build with threading support? */
  PyEval_InitThreads();
  #endif
  #endif
  /*--- Module creation code ---*/
  #if PY_MAJOR_VERSION < 3
  __pyx_m = Py_InitModule4(__Pyx_NAMESTR("cython_struct"), __pyx_methods, 0, 0, PYTHON_API_VERSION);
  #else
  __pyx_m = PyModule_Create(&__pyx_moduledef);
  #endif
  if (!__pyx_m) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;};
  #if PY_MAJOR_VERSION < 3
  Py_INCREF(__pyx_m);
  #endif
  __pyx_b = PyImport_AddModule(__Pyx_NAMESTR(__Pyx_BUILTIN_MODULE_NAME));
  if (!__pyx_b) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;};
  if (__Pyx_SetAttrString(__pyx_m, "__builtins__", __pyx_b) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;};
  /*--- Initialize various global constants etc. ---*/
  if (unlikely(__Pyx_InitGlobals() < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
  if (__pyx_module_is_main_cython_struct) {
    if (__Pyx_SetAttrString(__pyx_m, "__name__", __pyx_n_s____main__) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;};
  }
  /*--- Builtin init code ---*/
  if (unlikely(__Pyx_InitCachedBuiltins() < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
  /*--- Constants init code ---*/
  if (unlikely(__Pyx_InitCachedConstants() < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
  /*--- Global init code ---*/
  /*--- Variable export code ---*/
  /*--- Function export code ---*/
  /*--- Type init code ---*/
  /*--- Type import code ---*/
  /*--- Variable import code ---*/
  /*--- Function import code ---*/
  /*--- Execution code ---*/

  /* "cython_struct.pyx":8
 *     cdef void showStruct(myStruct *mst)
 * 
 * def test_struct():             # <<<<<<<<<<<<<<
 *     cdef myStruct mst
 *     initStruct(&mst)
 */
  __pyx_t_1 = PyCFunction_NewEx(&__pyx_mdef_13cython_struct_test_struct, NULL, __pyx_n_s__cython_struct); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 8; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
  __Pyx_GOTREF(__pyx_t_1);
  if (PyObject_SetAttr(__pyx_m, __pyx_n_s__test_struct, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 8; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
  __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;

  /* "cython_struct.pyx":1
 * cdef extern from "struct_test.h":             # <<<<<<<<<<<<<<
 *     ctypedef struct myStruct:
 *         int a
 */
  __pyx_t_1 = PyDict_New(); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
  __Pyx_GOTREF(((PyObject *)__pyx_t_1));
  if (PyObject_SetAttr(__pyx_m, __pyx_n_s____test__, ((PyObject *)__pyx_t_1)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
  __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0;
  goto __pyx_L0;
  __pyx_L1_error:;
  __Pyx_XDECREF(__pyx_t_1);
  if (__pyx_m) {
    __Pyx_AddTraceback("init cython_struct", __pyx_clineno, __pyx_lineno, __pyx_filename);
    Py_DECREF(__pyx_m); __pyx_m = 0;
  } else if (!PyErr_Occurred()) {
    PyErr_SetString(PyExc_ImportError, "init cython_struct");
  }
  __pyx_L0:;
  __Pyx_RefNannyFinishContext();
  #if PY_MAJOR_VERSION < 3
  return;
  #else
  return __pyx_m;
  #endif
}
开发者ID:kawasaki2013,项目名称:archive,代码行数:101,代码来源:cython_struct.c

示例4: RARCH_LOG

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;
}
开发者ID:AbelFlos,项目名称:RetroArch,代码行数:73,代码来源:py_state.c

示例5: buildModel

    Model buildModel(const std::string & filename, const std::string & model_name, bool verbose) throw (bp::error_already_set)
    {
      Py_Initialize();

      bp::object main_module = bp::import("__main__");
      // Get a dict for the global namespace to exec further python code with
      bp::dict globals = bp::extract<bp::dict>(main_module.attr("__dict__"));

      // We need to link to the pinocchio PyWrap. We delegate the dynamic loading to the python interpreter.
      bp::object cpp_module( (bp::handle<>(bp::borrowed(PyImport_AddModule("libpinocchio_pywrap")))) );

      // That's it, you can exec your python script, starting with a model you
      // can update as you want.
      try
      {
// Boost 1.58
#if BOOST_VERSION / 100 % 1000 == 58
        // Avoid a segv with exec_file
        // See: https://github.com/boostorg/python/pull/15
        std::ifstream t(filename.c_str());
        std::stringstream buffer;
        buffer << t.rdbuf();
        bp::exec(buffer.str().c_str(), globals);
#else // default implementation
        bp::exec_file((bp::str)filename, globals);
#endif
      }
      catch (bp::error_already_set & e)
      {
        PyErr_PrintEx(0);
      }

      Model model;
      try
      {
        bp::object obj_model = globals[model_name];
        model = bp::extract<Model>(obj_model);
      }
      catch (bp::error_already_set & e)
      {
        PyErr_PrintEx(0);
      }
      if (verbose)
      {
        std::cout << "Your model has been built. It has " << model.nv;
        std::cout << " degrees of freedom." << std::endl;
      }

      // close the interpreter
      // cf. https://github.com/numpy/numpy/issues/8097
#if PY_MAJOR_VERSION < 3
      Py_Finalize();
#else

      PyObject * poMainModule = PyImport_AddModule("__main__");
      PyObject * poAttrList = PyObject_Dir(poMainModule);
      PyObject * poAttrIter = PyObject_GetIter(poAttrList);
      PyObject * poAttrName;

      while ((poAttrName = PyIter_Next(poAttrIter)) != NULL)
      {
        std::string oAttrName = PyUnicode_AS_DATA(poAttrName);

        // Make sure we don't delete any private objects.
        if (!boost::starts_with(oAttrName, "__") || !boost::ends_with(oAttrName, "__"))
        {
          PyObject * poAttr = PyObject_GetAttr(poMainModule, poAttrName);

          // Make sure we don't delete any module objects.
          if (poAttr && poAttr->ob_type != poMainModule->ob_type)
            PyObject_SetAttr(poMainModule, poAttrName, NULL);
          Py_DecRef(poAttr);
        }
        Py_DecRef(poAttrName);
      }
      Py_DecRef(poAttrIter);
      Py_DecRef(poAttrList);
#endif

      return model;
    }
开发者ID:nim65s,项目名称:pinocchio,代码行数:81,代码来源:model.cpp

示例6: PyImport_AddModule

mitk::Image::Pointer mitk::PythonService::CopySimpleItkImageFromPython(const std::string &stdvarName)
{
  double*ds = NULL;
  // access python module
  PyObject *pyMod = PyImport_AddModule((char*)"__main__");
  // global dictionarry
  PyObject *pyDict = PyModule_GetDict(pyMod);
  mitk::Image::Pointer mitkImage = mitk::Image::New();
  mitk::Vector3D spacing;
  mitk::Point3D origin;
  QString command;
  QString varName = QString::fromStdString( stdvarName );

  command.append( QString("%1_numpy_array = sitk.GetArrayFromImage(%1)\n").arg(varName) );
  command.append( QString("%1_spacing = numpy.asarray(%1.GetSpacing())\n").arg(varName) );
  command.append( QString("%1_origin = numpy.asarray(%1.GetOrigin())\n").arg(varName) );
  command.append( QString("%1_dtype = %1_numpy_array.dtype.name").arg(varName) );

  MITK_DEBUG("PythonService") << "Issuing python command " << command.toStdString();
  this->Execute(command.toStdString(), IPythonService::MULTI_LINE_COMMAND );

  PyObject* py_dtype = PyDict_GetItemString(pyDict,QString("%1_dtype").arg(varName).toStdString().c_str() );
  std::string dtype = PyString_AsString(py_dtype);
  PyArrayObject* py_data = (PyArrayObject*) PyDict_GetItemString(pyDict,QString("%1_numpy_array").arg(varName).toStdString().c_str() );
  PyArrayObject* py_spacing = (PyArrayObject*) PyDict_GetItemString(pyDict,QString("%1_spacing").arg(varName).toStdString().c_str() );
  PyArrayObject* py_origin = (PyArrayObject*) PyDict_GetItemString(pyDict,QString("%1_origin").arg(varName).toStdString().c_str() );

  size_t sz = sizeof(short);
  mitk::PixelType pixelType = MakeScalarPixelType<short>();
  if( dtype.compare("float64") == 0   ) {
    pixelType = MakeScalarPixelType<double>();
    sz = sizeof(double);
  } else if( dtype.compare("float32") == 0 ) {
    pixelType = MakeScalarPixelType<float>();
    sz = sizeof(float);
  } else if( dtype.compare("int16") == 0) {
    pixelType = MakeScalarPixelType<short>();
    sz = sizeof(short);
  } else if( dtype.compare("int8") == 0 ) {
    pixelType = MakeScalarPixelType<char>();
    sz = sizeof(char);
  } else if( dtype.compare("int32") == 0 ) {
    pixelType = MakeScalarPixelType<int>();
    sz = sizeof(int);
  } else if( dtype.compare("int64") == 0 ) {
    pixelType = MakeScalarPixelType<long>();
    sz = sizeof(long);
  } else if( dtype.compare("uint8") == 0 ) {
    pixelType = MakeScalarPixelType<unsigned char>();
    sz = sizeof(unsigned char);
  } else if( dtype.compare("uint32") == 0 ) {
    pixelType = MakeScalarPixelType<unsigned int>();
    sz = sizeof(unsigned int);
  } else if( dtype.compare("uint64") == 0 ) {
    pixelType = MakeScalarPixelType<unsigned long>();
    sz = sizeof(unsigned long);
  } else if( dtype.compare("uint16") == 0 ) {
    pixelType = MakeScalarPixelType<unsigned short>();
    sz = sizeof(unsigned short);
  }

  unsigned int* dimensions = new unsigned int[py_data->nd];
  // fill backwards , nd data saves dimensions in opposite direction
  for( int i = 0; i < py_data->nd; ++i )
  {
    dimensions[i] = py_data->dimensions[py_data->nd - 1 - i];
    sz *= dimensions[i];
  }

  mitkImage->Initialize(pixelType, py_data->nd, dimensions);
  mitkImage->SetChannel(py_data->data);

  ds = (double*)py_spacing->data;
  spacing[0] = ds[0];
  spacing[1] = ds[1];
  spacing[2] = ds[2];
  mitkImage->GetGeometry()->SetSpacing(spacing);

  ds = (double*)py_origin->data;
  origin[0] = ds[0];
  origin[1] = ds[1];
  origin[2] = ds[2];
  mitkImage->GetGeometry()->SetOrigin(origin);

  // cleanup
  command.clear();
  command.append( QString("del %1_numpy_array\n").arg(varName) );
  command.append( QString("del %1_dtype\n").arg(varName) );
  command.append( QString("del %1_spacing\n").arg(varName) );
  command.append( QString("del %1_origin").arg(varName) );
  MITK_DEBUG("PythonService") << "Issuing python command " << command.toStdString();
  this->Execute(command.toStdString(), IPythonService::MULTI_LINE_COMMAND );

  delete[] dimensions;

  return mitkImage;
}
开发者ID:DiagnosisMultisystems,项目名称:MITK,代码行数:97,代码来源:mitkPythonService.cpp

示例7: get_plots

bool get_plots(const std::string& python_file, std::vector<Plot>& plots) {

    plots.clear();

    std::FILE* f = std::fopen(python_file.c_str(), "r");
    if (!f) {
        std::cerr << "Failed to open '" << python_file << "'" <<std::endl;
        return false;
    }

    const std::string PLOTS_KEY_NAME = "plots";

    // Get a reference to the main module
    // and global dictionary
    PyObject* main_module = PyImport_AddModule("__main__");
    PyObject* global_dict = PyModule_GetDict(main_module);

    // If PyROOT is used inside the script, it performs some cleanups when the python env. is destroyed. This cleanup makes ROOT unusable afterwards.
    // The cleanup function is registered with the `atexit` module.
    // The solution is to not execute the cleanup function. For that, before destroying the python env, we check the list of exit functions,
    // and delete the one from PyROOT if found

    // Ensure the module is loaded
    PyObject* atexit_module = PyImport_ImportModule("atexit");

    // Execute the script
    PyObject* script_result = PyRun_File(f, python_file.c_str(), Py_file_input, global_dict, global_dict);

    if (! script_result) {
        PyErr_Print();
        return false;
    } else {
        PyObject* py_plots = PyDict_GetItemString(global_dict, "plots");
        if (!py_plots) {
            std::cerr << "No 'plots' variable declared in python script" << std::endl;
            return false;
        }

        if (! PyList_Check(py_plots)) {
            std::cerr << "The 'plots' variable is not a list" << std::endl;
            return false;
        }

        size_t l = PyList_Size(py_plots);
        if (! l)
            return true;

        for (size_t i = 0; i < l; i++) {
            PyObject* item = PyList_GetItem(py_plots, i);

            Plot plot;
            if (plot_from_PyObject(item, plot)) {
                plots.push_back(plot);
            }
        }
    }

    PyObject* atexit_exithandlers = PyObject_GetAttrString(atexit_module, "_exithandlers");
    for (size_t i = 0; i < PySequence_Size(atexit_exithandlers); i++) {
        PyObject* tuple = PySequence_GetItem(atexit_exithandlers, i);
        PyObject* f = PySequence_GetItem(tuple, 0);
        PyObject* module = PyFunction_GetModule(f);

        if (module && strcmp(PyString_AsString(module), "ROOT") == 0) {
            PySequence_DelItem(atexit_exithandlers, i);
            break;
        }
    }

    return true;
}
开发者ID:sdevissc,项目名称:CommonTools,代码行数:71,代码来源:createPlotter.cpp

示例8: py_execute

bool py_execute(PyCodeObject* py_func, DSMSession* sc_sess, 
		DSMCondition::EventType event, map<string,string>* event_params,
		bool expect_int_result) {
  // acquire the GIL
  PYLOCK;

  bool py_res = false;
  DBG("add main \n");
  PyObject* m = PyImport_AddModule("__main__");
  if (m == NULL) {
    ERROR("getting main module\n");
    return false;
  }
  DBG("get globals \n");
  PyObject* globals = PyModule_GetDict(m);
  PyObject* locals = getPyLocals(sc_sess);

  PyObject* params = PyDict_New();
  if (NULL != event_params) {
    for (map<string,string>::iterator it=event_params->begin(); 
	 it != event_params->end(); it++) {
      PyObject* v = PyString_FromString(it->second.c_str());
      PyDict_SetItemString(params, it->first.c_str(), v);
      Py_DECREF(v);
    }
  }
  PyDict_SetItemString(locals, "params", params);

  PyObject *t = PyInt_FromLong(event);
  PyDict_SetItemString(locals, "type", t);

  PyObject* py_sc_sess = PyCObject_FromVoidPtr(sc_sess,NULL);
  PyObject* ts_dict = PyThreadState_GetDict();
  PyDict_SetItemString(ts_dict, "_dsm_sess_", py_sc_sess);
  Py_DECREF(py_sc_sess);

  // call the function
  PyObject* res = PyEval_EvalCode((PyCodeObject*)py_func, globals, locals);

  if(PyErr_Occurred())
    PyErr_Print();

  PyDict_DelItemString(locals, "params");
  PyDict_Clear(params);
  Py_DECREF(params);

  PyDict_DelItemString(locals, "type");
  Py_DECREF(t);
  
  //   ts_dict = PyThreadState_GetDict(); // should be the same as before
  PyDict_DelItemString(ts_dict, "_dsm_sess_");
  
  if (NULL == res) {
    ERROR("evaluating python code\n");
  } else if (PyBool_Check(res)) {
    py_res = PyInt_AsLong(res);
    Py_DECREF(res);
  } else {
    if (expect_int_result) {
      ERROR("unknown result from python code\n");
    }
    Py_DECREF(res);
  }

  return py_res;
}
开发者ID:bjtpartners,项目名称:sems-mysql-routing,代码行数:66,代码来源:ModPy.cpp

示例9: mainThread

uint32_t mainThread(int argc, char *argv[], bool so) {

	int rc = 0;
	PyObject *m=NULL, *d=NULL, *seq=NULL;
	PyObject *mod;
	char * ppath;
	FILE * f;
	uintptr_t cookie = 0;
	PyGILState_STATE restore_state;

	if(!Py_IsInitialized) {
		int res=0;

		if(!_load_python(
				"libpython2.7.so",
				resources_python27_so_start,
				resources_python27_so_size)) {
			dprint("loading libpython2.7.so from memory failed\n");
			return -1;
		}
	}

	dprint("calling PyEval_InitThreads() ...\n");
	PyEval_InitThreads();
	dprint("PyEval_InitThreads() called\n");

	if(!Py_IsInitialized()) {
		dprint("Py_IsInitialized\n");

		Py_IgnoreEnvironmentFlag = 1;
		Py_NoSiteFlag = 1; /* remove site.py auto import */

		dprint("INVOCATION NAME: %s\n", program_invocation_name);
		Py_SetProgramName(program_invocation_name);

		dprint("Initializing python.. (%p)\n", Py_Initialize);
		Py_InitializeEx(0);

		dprint("SET ARGV\n");
		if (argc > 0) {
			if (so) {
				if (argc > 2 && !strcmp(argv[1], "--pass-args")) {
					argv[1] = argv[0];
					PySys_SetArgvEx(argc - 1, argv + 1, 0);
				} else {
					PySys_SetArgvEx(1, argv, 0);
				}
			} else {
				PySys_SetArgvEx(argc, argv, 0);
			}
		}

		PySys_SetPath(".");
#ifndef DEBUG
		PySys_SetObject("frozen", PyBool_FromLong(1));
#endif

		dprint("Py_Initialize() complete\n");
	}
	restore_state=PyGILState_Ensure();

	init_memimporter();
	dprint("init_memimporter()\n");
	initpupy();
	dprint("initpupy()\n");

#ifdef _PYZLIB_DYNLOAD
	dprint("load zlib\n");
    if (!import_module("initzlib", "zlib", resources_zlib_so_start, resources_zlib_so_size)) {
        dprint("ZLib load failed.\n");
    }
#endif

	/* We execute then in the context of '__main__' */
	dprint("starting evaluating python code ...\n");
	m = PyImport_AddModule("__main__");
	if (m) d = PyModule_GetDict(m);
	if (d) seq = PyMarshal_ReadObjectFromString(
		resources_bootloader_pyc_start,
		resources_bootloader_pyc_size
	);

	if (seq) {
		Py_ssize_t i, max = PySequence_Length(seq);
		for (i=0;i<max;i++) {
			dprint("LOAD SEQUENCE %d\n", i);
			PyObject *sub = PySequence_GetItem(seq, i);
			if (seq) {
				PyObject *discard = PyEval_EvalCode((PyCodeObject *)sub, d, d);
				if (!discard) {
					dprint("discard\n");
					PyErr_Print();
					rc = 255;
				}
				Py_XDECREF(discard);
				/* keep going even if we fail */
			}
			Py_XDECREF(sub);
		}
	}
//.........这里部分代码省略.........
开发者ID:dc3l1ne,项目名称:pupy,代码行数:101,代码来源:pupy_load.c

示例10: PyEval_AcquireLock

void XBPyThread::Process()
{
  CLog::Log(LOGDEBUG,"Python thread: start processing");

  int m_Py_file_input = Py_file_input;

  // get the global lock
  PyEval_AcquireLock();
  PyThreadState* state = Py_NewInterpreter();
  if (!state)
  {
    PyEval_ReleaseLock();
    CLog::Log(LOGERROR,"Python thread: FAILED to get thread state!");
    return;
  }
  // swap in my thread state
  PyThreadState_Swap(state);

  m_pExecuter->InitializeInterpreter(addon);

  CLog::Log(LOGDEBUG, "%s - The source file to load is %s", __FUNCTION__, m_source);

  // get path from script file name and add python path's
  // this is used for python so it will search modules from script path first
  CStdString scriptDir;
  URIUtils::GetDirectory(_P(m_source), scriptDir);
  URIUtils::RemoveSlashAtEnd(scriptDir);
  CStdString path = scriptDir;

  // add on any addon modules the user has installed
  ADDON::VECADDONS addons;
  ADDON::CAddonMgr::Get().GetAddons(ADDON::ADDON_SCRIPT_MODULE, addons);
  for (unsigned int i = 0; i < addons.size(); ++i)
#ifdef TARGET_WINDOWS
  {
    CStdString strTmp(_P(addons[i]->LibPath()));
    g_charsetConverter.utf8ToStringCharset(strTmp);
    path += PY_PATH_SEP + strTmp;
  }
#else
    path += PY_PATH_SEP + _P(addons[i]->LibPath());
#endif

  // and add on whatever our default path is
  path += PY_PATH_SEP;

  // we want to use sys.path so it includes site-packages
  // if this fails, default to using Py_GetPath
  PyObject *sysMod(PyImport_ImportModule((char*)"sys")); // must call Py_DECREF when finished
  PyObject *sysModDict(PyModule_GetDict(sysMod)); // borrowed ref, no need to delete
  PyObject *pathObj(PyDict_GetItemString(sysModDict, "path")); // borrowed ref, no need to delete

  if( pathObj && PyList_Check(pathObj) )
  {
    for( int i = 0; i < PyList_Size(pathObj); i++ )
    {
      PyObject *e = PyList_GetItem(pathObj, i); // borrowed ref, no need to delete
      if( e && PyString_Check(e) )
      {
          path += PyString_AsString(e); // returns internal data, don't delete or modify
          path += PY_PATH_SEP;
      }
    }
  }
  else
  {
    path += Py_GetPath();
  }
  Py_DECREF(sysMod); // release ref to sysMod

  // set current directory and python's path.
  if (m_argv != NULL)
    PySys_SetArgv(m_argc, m_argv);

  CLog::Log(LOGDEBUG, "%s - Setting the Python path to %s", __FUNCTION__, path.c_str());

  PySys_SetPath((char *)path.c_str());

  CLog::Log(LOGDEBUG, "%s - Entering source directory %s", __FUNCTION__, scriptDir.c_str());

  PyObject* module = PyImport_AddModule((char*)"__main__");
  PyObject* moduleDict = PyModule_GetDict(module);

  // when we are done initing we store thread state so we can be aborted
  PyThreadState_Swap(NULL);
  PyEval_ReleaseLock();

  // we need to check if we was asked to abort before we had inited
  bool stopping = false;
  { CSingleLock lock(m_pExecuter->m_critSection);
    m_threadState = state;
    stopping = m_stopping;
  }

  PyEval_AcquireLock();
  PyThreadState_Swap(state);

  if (!stopping)
  {
    if (m_type == 'F')
//.........这里部分代码省略.........
开发者ID:mireks,项目名称:xbmc,代码行数:101,代码来源:XBPyThread.cpp

示例11: PyRun_SimpleString

void Python_script::execute(const std::string grid_name, const std::vector<std::string> prop_names) const
{

	PyRun_SimpleString(""
		"import redirect\n"
		"class CoutLogger:\n"
		"    def __init__(self):\n"
		"        self.buf = []\n"
		"    def write(self, data):\n"
		"        self.buf.append(data)\n"
		"        if data.endswith('\\n'):\n"
		"            redirect.sgems_cout(''.join(self.buf))\n"
		"            self.buf = []\n"
		"\n"
		"class CerrLogger:\n"
		"    def __init__(self):\n"
		"        self.buf = []\n"
		"    def write(self, data):\n"
		"        self.buf.append(data)\n"
		"        if data.endswith('\\n'):\n"
		"            redirect.sgems_cerr(''.join(self.buf))\n"
		"            self.buf = []\n"
		"\n"
		"import sys\n"
		"sys.stdout = CoutLogger()\n"
		"sys.stderr = CerrLogger()\n"
		"");

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

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

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

	PyObject* function = PyDict_GetItemString(dictionary_copy, "sgems_execute_action");
	if (PyCallable_Check(function))
	{
		//		PyObject* properties = Py_BuildValue("[ss]", prop_names.at(0).c_str(), prop_names.at(0).c_str());
		//		if (NULL == properties)
		//		{
		//			std::cout << "building value failed\n";
		//		}
		//		PyObject* properties = PyList_New(prop_names.size());
		//		for (int i = 0; i < prop_names.size(); ++i)
		//		{
		//			PyList_SetItem(properties, i, PyString_FromString(prop_names.at(i).c_str()));
		//		}
		//		PyObject* result = PyObject_CallFunction(function, "s[o]", grid_name.c_str(), properties);

		PyObject* result = NULL;

		switch (prop_names.size())
		{
		case 1:
			result = PyObject_CallFunction(function, "s[s]", grid_name.c_str(), prop_names.at(0).c_str());
			break;
		case 2:
			result = PyObject_CallFunction(function, "s[ss]", grid_name.c_str(), prop_names.at(0).c_str(), prop_names.at(1).c_str());
			break;
		default:
			GsTLcerr << "Execution of python script failed.\n Cannot have more than 2 properties selected\n" << gstlIO::end;
			break;
		}

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

		Py_XDECREF(result);
	}

	Py_XDECREF(dictionary_copy);
	fclose(fp);
}
开发者ID:TUDz,项目名称:ar2tech-SGeMS-public,代码行数:82,代码来源:python_script.cpp

示例12: __pyx_init_filenames

/* Implementation of cforfromloop */

static struct PyMethodDef __pyx_methods[] = {
  {0, 0, 0, 0}
};

static void __pyx_init_filenames(void); /*proto*/

PyMODINIT_FUNC initcforfromloop(void); /*proto*/
PyMODINIT_FUNC initcforfromloop(void) {
  long __pyx_1;
  PyObject *__pyx_2 = 0;
  long __pyx_3;
  int __pyx_4;
  __pyx_init_filenames();
  __pyx_m = Py_InitModule4("cforfromloop", __pyx_methods, 0, 0, PYTHON_API_VERSION);
  if (!__pyx_m) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; goto __pyx_L1;};
  Py_INCREF(__pyx_m);
  __pyx_b = PyImport_AddModule("__builtin__");
  if (!__pyx_b) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; goto __pyx_L1;};
  if (PyObject_SetAttrString(__pyx_m, "__builtins__", __pyx_b) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; goto __pyx_L1;};
  if (__Pyx_InitStrings(__pyx_string_tab) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; goto __pyx_L1;};
  __pyx_v_12cforfromloop_a = Py_None; Py_INCREF(Py_None);
  __pyx_v_12cforfromloop_b = Py_None; Py_INCREF(Py_None);
  __pyx_v_12cforfromloop_x = Py_None; Py_INCREF(Py_None);

  /* "/Local/Projects/D/Pyrex/Source/Tests/7/cforfromloop.pyx":4 */
  for (__pyx_v_12cforfromloop_i = 0; __pyx_v_12cforfromloop_i < 10; ++__pyx_v_12cforfromloop_i) {
  }

  /* "/Local/Projects/D/Pyrex/Source/Tests/7/cforfromloop.pyx":7 */
  for (__pyx_v_12cforfromloop_i = 0+1; __pyx_v_12cforfromloop_i <= 10; ++__pyx_v_12cforfromloop_i) {
  }

  /* "/Local/Projects/D/Pyrex/Source/Tests/7/cforfromloop.pyx":10 */
  for (__pyx_v_12cforfromloop_i = 10; __pyx_v_12cforfromloop_i > 0; --__pyx_v_12cforfromloop_i) {
  }

  /* "/Local/Projects/D/Pyrex/Source/Tests/7/cforfromloop.pyx":13 */
  for (__pyx_v_12cforfromloop_i = 10-1; __pyx_v_12cforfromloop_i >= 0; --__pyx_v_12cforfromloop_i) {
  }

  /* "/Local/Projects/D/Pyrex/Source/Tests/7/cforfromloop.pyx":16 */
  for (__pyx_1 = 0; __pyx_1 <= 10; ++__pyx_1) {
    __pyx_2 = PyInt_FromLong(__pyx_1); if (!__pyx_2) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 16; goto __pyx_L1;}
    Py_DECREF(__pyx_v_12cforfromloop_x);
    __pyx_v_12cforfromloop_x = __pyx_2;
    __pyx_2 = 0;
  }

  /* "/Local/Projects/D/Pyrex/Source/Tests/7/cforfromloop.pyx":19 */
  __pyx_1 = PyInt_AsLong(__pyx_v_12cforfromloop_a); if (PyErr_Occurred()) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 19; goto __pyx_L1;}
  __pyx_3 = PyInt_AsLong(__pyx_v_12cforfromloop_b); if (PyErr_Occurred()) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 19; goto __pyx_L1;}
  for (__pyx_v_12cforfromloop_i = __pyx_1; __pyx_v_12cforfromloop_i <= __pyx_3; ++__pyx_v_12cforfromloop_i) {
  }

  /* "/Local/Projects/D/Pyrex/Source/Tests/7/cforfromloop.pyx":22 */
  for (__pyx_v_12cforfromloop_i = __pyx_v_12cforfromloop_k; __pyx_v_12cforfromloop_i <= __pyx_v_12cforfromloop_j; ++__pyx_v_12cforfromloop_i) {
  }

  /* "/Local/Projects/D/Pyrex/Source/Tests/7/cforfromloop.pyx":25 */
  __pyx_1 = (__pyx_v_12cforfromloop_j / 18);
  for (__pyx_v_12cforfromloop_i = (__pyx_v_12cforfromloop_k * 42); __pyx_v_12cforfromloop_i <= __pyx_1; ++__pyx_v_12cforfromloop_i) {
  }

  /* "/Local/Projects/D/Pyrex/Source/Tests/7/cforfromloop.pyx":28 */
  while (1) {
    __pyx_4 = __pyx_v_12cforfromloop_j;
    if (!__pyx_4) break;
    for (__pyx_v_12cforfromloop_i = 0; __pyx_v_12cforfromloop_i <= 10; ++__pyx_v_12cforfromloop_i) {

      /* "/Local/Projects/D/Pyrex/Source/Tests/7/cforfromloop.pyx":30 */
      goto __pyx_L20;

      /* "/Local/Projects/D/Pyrex/Source/Tests/7/cforfromloop.pyx":31 */
      goto __pyx_L21;
      __pyx_L20:;
    }
    /*else*/ {

      /* "/Local/Projects/D/Pyrex/Source/Tests/7/cforfromloop.pyx":33 */
      goto __pyx_L18;

      /* "/Local/Projects/D/Pyrex/Source/Tests/7/cforfromloop.pyx":34 */
      goto __pyx_L19;
    }
    __pyx_L21:;
    __pyx_L18:;
  }
  __pyx_L19:;
  return;
  __pyx_L1:;
  Py_XDECREF(__pyx_2);
  __Pyx_AddTraceback("cforfromloop");
}
开发者ID:jwilk,项目名称:Pyrex,代码行数:95,代码来源:cforfromloop.c

示例13: run_interpreter

static void
run_interpreter(FILE *input, FILE *output)
{
	PyThreadState *tstate;
	PyObject *new_stdin, *new_stdout;
	PyObject *mainmod, *globals;
	char buffer[1000];
	char *p, *q;
	int n, end;

	PyEval_AcquireLock();
	tstate = Py_NewInterpreter();
	if (tstate == NULL) {
		fprintf(output, "Sorry -- can't create an interpreter\n");
		return;
	}

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

	new_stdin = PyFile_FromFile(input, "<socket-in>", "r", NULL);
	new_stdout = PyFile_FromFile(output, "<socket-out>", "w", NULL);

	PySys_SetObject("stdin", new_stdin);
	PySys_SetObject("stdout", new_stdout);
	PySys_SetObject("stderr", new_stdout);

	for (n = 1; !PyErr_Occurred(); n++) {
		Py_BEGIN_ALLOW_THREADS
		fprintf(output, "%d> ", n);
		p = fgets(buffer, sizeof buffer, input);
		Py_END_ALLOW_THREADS

		if (p == NULL)
			break;
		if (p[0] == '\377' && p[1] == '\354')
			break;

		q = strrchr(p, '\r');
		if (q && q[1] == '\n' && q[2] == '\0') {
			*q++ = '\n';
			*q++ = '\0';
		}

		while (*p && isspace(*p))
			p++;
		if (p[0] == '#' || p[0] == '\0')
			continue;

		end = run_command(buffer, globals);
		if (end < 0)
			PyErr_Print();

		if (end)
			break;
	}

	Py_XDECREF(globals);
	Py_XDECREF(new_stdin);
	Py_XDECREF(new_stdout);

	Py_EndInterpreter(tstate);
	PyEval_ReleaseLock();

	fprintf(output, "Goodbye!\n");
}
开发者ID:asottile,项目名称:ancient-pythons,代码行数:67,代码来源:pysvr.c

示例14: uwsgi_log

PyObject *uwsgi_pyimport_by_filename(char *name, char *filename) {

#ifdef UWSGI_PYPY
	uwsgi_log("import by filename is currently not supported on PyPy !!!\n");
	return NULL;
#else
	FILE *pyfile;
	struct _node *py_file_node = NULL;
	PyObject *py_compiled_node, *py_file_module;
	int is_a_package = 0;
	struct stat pystat;
	char *real_filename = filename;


	if (!uwsgi_check_scheme(filename)) {

		pyfile = fopen(filename, "r");
		if (!pyfile) {
			uwsgi_log("failed to open python file %s\n", filename);
			return NULL;
		}

		if (fstat(fileno(pyfile), &pystat)) {
			uwsgi_error("fstat()");
			return NULL;
		}

		if (S_ISDIR(pystat.st_mode)) {
			is_a_package = 1;
			fclose(pyfile);
			real_filename = uwsgi_concat2(filename, "/__init__.py");
			pyfile = fopen(real_filename, "r");
			if (!pyfile) {
				uwsgi_error_open(real_filename);
				free(real_filename);
				return NULL;
			}
		}

		py_file_node = PyParser_SimpleParseFile(pyfile, real_filename, Py_file_input);
		if (!py_file_node) {
			PyErr_Print();
			uwsgi_log("failed to parse file %s\n", real_filename);
			if (is_a_package)
				free(real_filename);
			fclose(pyfile);
			return NULL;
		}

		fclose(pyfile);
	}
	else {
		int pycontent_size = 0;
		char *pycontent = uwsgi_open_and_read(filename, &pycontent_size, 1, NULL);

		if (pycontent) {
			py_file_node = PyParser_SimpleParseString(pycontent, Py_file_input);
			if (!py_file_node) {
				PyErr_Print();
				uwsgi_log("failed to parse url %s\n", real_filename);
				return NULL;
			}
		}
	}

	py_compiled_node = (PyObject *) PyNode_Compile(py_file_node, real_filename);

	if (!py_compiled_node) {
		PyErr_Print();
		uwsgi_log("failed to compile python file %s\n", real_filename);
		return NULL;
	}

	if (is_a_package) {
		py_file_module = PyImport_AddModule(name);
		if (py_file_module) {
			PyModule_AddObject(py_file_module, "__path__", Py_BuildValue("[O]", PyString_FromString(filename)));
		}
		free(real_filename);
	}

	py_file_module = PyImport_ExecCodeModule(name, py_compiled_node);
	if (!py_file_module) {
		PyErr_Print();
		return NULL;
	}

	Py_DECREF(py_compiled_node);

	return py_file_module;
#endif

}
开发者ID:rebx,项目名称:uwsgi,代码行数:93,代码来源:python_plugin.c

示例15: init_uwsgi_embedded_module

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);
        	}
	}
//.........这里部分代码省略.........
开发者ID:rebx,项目名称:uwsgi,代码行数:101,代码来源:python_plugin.c


注:本文中的PyImport_AddModule函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。