Beispiel #1
0
PythonModules::PythonModules(QString name, Pip3lineCallback *callback) :
    ModulesManagement(name, PYTHON_EXTENSION, BASE_SCRIPTS_DIR, callback)
{

    pyGetValFunc = nullptr;
    pyStringIO = nullptr;
    pyTruncateFunc = nullptr;
    pySeekFunc = nullptr;

    Py_SetProgramName(PROG_NAME);
    Py_DontWriteBytecodeFlag++;

#if defined(Q_OS_WIN) && !defined(BUILD_PYTHON_3)
    pythonPath = PythonModules::initPythonPath();
    Py_SetPythonHome(pythonPath);
#endif //Q_OS_WIN && !BUILD_PYTHON_3

    // initialize the Python interpreter without signal handler
    Py_InitializeEx(0);
    // initialize thread support
    PyEval_InitThreads();
    // saving thread state
    pymainstate = PyEval_SaveThread();

   connect(this, &PythonModules::pathsUpdated, this, &PythonModules::updatePath);
   qDebug() << "Created " << this;

}
Beispiel #2
0
bool CmdSrvHosts::processArguments( int argc, char** argv, af::Msg &msg)
{
   Py_InitializeEx(0);

   std::string command( argv[1]);
   std::list<std::string> hosts;
   for( int a = 2; a < argc; a++) hosts.push_back( argv[a]);

   std::string wdir;
   int capacity = -1;
   std::string files;

   af::Service service( argv[0], wdir, command, files, capacity, hosts);
   if( service.isInitialized() == false)
   {
      AFERRAR("Service '%s' initialization failed.\n", argv[0]);
      return false;
   }

   command = service.getCommand();
   std::cout << "Result Command:";
   std::cout << std::endl;
   std::cout << command;
   std::cout << std::endl;

   Py_Finalize();

   return true;
}
Beispiel #3
0
void PyInviwo::initPythonCInterface() {
    if (isInit_) return;

    isInit_ = true;
    LogInfo("Python version: " + toString(Py_GetVersion()));
    wchar_t programName[] = L"PyInviwo";
    Py_SetProgramName(programName);
#ifdef WIN32
    Py_NoSiteFlag = 1;
#endif
    Py_InitializeEx(false);

    if (!Py_IsInitialized()) {
        LogError("Python is not Initialized");
        return;
    }

    PyEval_InitThreads();
    mainDict_ = PyDict_New();
    modulesDict_ = PyImport_GetModuleDict();
    importModule("builtins");
    importModule("sys");
    importModule("os");
    importModule("glob");
    importModule("random");


    addModulePath(InviwoApplication::getPtr()->getBasePath() + "/modules/python3/scripts");

    initDefaultInterfaces();

    initOutputRedirector();
}
Beispiel #4
0
/* Initialize Python interpreter */
static void python_system_init(lua_State *L) {
    char *python_home = luaL_check_string(L, 1);
    if (!Py_IsInitialized()) {
        python_setnumber(L, PY_API_IS_EMBEDDED, 1); // If python is inside Lua
        if (PyType_Ready(&LuaObject_Type) == 0) {
            Py_INCREF(&LuaObject_Type);
        } else {
            lua_error(L, "failure initializing lua object type");
        }
        PyObject *luam, *mainm, *maind;
#if PY_MAJOR_VERSION >= 3
        wchar_t *argv[] = {L"<lua_bootstrap>", 0};
#else
        char *argv[] = {"<lua_bootstrap>", 0};
#endif
        Py_SetProgramName(argv[0]);
        Py_SetPythonHome(python_home);
        Py_InitializeEx(0);
        PySys_SetArgv(1, argv);
        /* Import 'lua' automatically. */
        luam = PyImport_ImportModule("lua_bootstrap");
        if (!luam) {
            lua_error(L, "Can't import lua_bootstrap module");
        } else {
            mainm = PyImport_AddModule("__main__");
            if (!mainm) {
                lua_error(L, "Can't get __main__ module");
            } else {
                maind = PyModule_GetDict(mainm);
                PyDict_SetItemString(maind, "lua_bootstrap", luam);
                Py_DECREF(luam);
            }
        }
    }
}
Beispiel #5
0
void PyInviwo::initPythonCInterface(Python3Module* module) {
    if (isInit_) return;

    isInit_ = true;
    LogInfo("Python version: " + toString(Py_GetVersion()));
    wchar_t programName[] = L"PyInviwo";
    Py_SetProgramName(programName);

    Py_InitializeEx(false);

    if (!Py_IsInitialized()) {
        LogError("Python is not Initialized");
        return;
    }

    PyEval_InitThreads();
    importModule("builtins");
    importModule("sys");

    dict_ = PyImport_GetModuleDict();
    registerPyModule(&Inviwo_Internals_Module_Def, "inviwo_internal");
    registerPyModule(&Inviwo_Module_Def, "inviwo");

    addModulePath(module->getPath() + "/scripts");
    initOutputRedirector(module);
}
Beispiel #6
0
static int mod_init(rlm_python_t *inst)
{
	int i;
	static char name[] = "radiusd";

	if (radiusd_module) return 0;

	/*
	 *	Explicitly load libpython, so symbols will be available to lib-dynload modules
	 */
	inst->libpython = dlopen("libpython" STRINGIFY(PY_MAJOR_VERSION) "." STRINGIFY(PY_MINOR_VERSION) ".so",
				 RTLD_NOW | RTLD_GLOBAL);
	if (!inst->libpython) {
	 	WARN("Failed loading libpython symbols into global symbol table: %s", dlerror());
	}

	Py_SetProgramName(name);
#ifdef HAVE_PTHREAD_H
	Py_InitializeEx(0);				/* Don't override signal handlers */
	PyEval_InitThreads(); 				/* This also grabs a lock */
	inst->main_thread_state = PyThreadState_Get();	/* We need this for setting up thread local stuff */
#endif
	if (inst->python_path) {
		PySys_SetPath(inst->python_path);
	}

	if ((radiusd_module = Py_InitModule3("radiusd", radiusd_methods,
					     "FreeRADIUS Module.")) == NULL)
		goto failed;

	for (i = 0; radiusd_constants[i].name; i++) {
		if ((PyModule_AddIntConstant(radiusd_module, radiusd_constants[i].name,
					     radiusd_constants[i].value)) < 0) {
			goto failed;
		}
	}

#ifdef HAVE_PTHREAD_H
	PyThreadState_Swap(NULL);	/* We have to swap out the current thread else we get deadlocks */
	PyEval_ReleaseLock();		/* Drop lock grabbed by InitThreads */
#endif
	DEBUG("mod_init done");
	return 0;

failed:
	Py_XDECREF(radiusd_module);

#ifdef HAVE_PTHREAD_H
	PyEval_ReleaseLock();
#endif

	Pyx_BLOCK_THREADS
	mod_error();
	Pyx_UNBLOCK_THREADS

	radiusd_module = NULL;

	Py_Finalize();
	return -1;
}
Beispiel #7
0
void python_init(void)
{
    Py_InitializeEx(0);

    pysignals_init();
    pystatusbar_init();
    if (!pyloader_init() || !pymodule_init() || !factory_init() || !pythemes_init()) 
    {
        printtext(NULL, NULL, MSGLEVEL_CLIENTERROR, "Failed to load Python");
        return;
    }
    pyconstants_init();

    /*PyImport_ImportModule("irssi_startup");*/
    /* Install the custom output handlers, import hook and reload function */
    /* XXX: handle import error */
    PyRun_SimpleString(
            "import irssi_startup\n"
    );

    pyloader_auto_load();
    
    /* assert(signal(SIGINT, intr_catch) != SIG_ERR); */
    
    command_bind("py", NULL, (SIGNAL_FUNC) cmd_default);
    command_bind("py load", NULL, (SIGNAL_FUNC) cmd_load);
    command_bind("py unload", NULL, (SIGNAL_FUNC) cmd_unload);
    command_bind("py list", NULL, (SIGNAL_FUNC) cmd_list);
    command_bind("py exec", NULL, (SIGNAL_FUNC) cmd_exec);
    module_register(MODULE_NAME, "core");
}
Beispiel #8
0
//! Initializes Python VM
int
script_init()
{
    Py_InitializeEx(0);

    // Initialize exceptions
    PyExc_COMAR_Internal = PyErr_NewException("Comar.Internal", NULL, NULL);
    PyExc_COMAR_Invalid = PyErr_NewException("Comar.Invalid", NULL, NULL);
    PyExc_COMAR_Script = PyErr_NewException("Comar.Script", NULL, NULL);
    PyExc_COMAR_Missing = PyErr_NewException("Comar.Missing", NULL, NULL);
    PyExc_DBus = PyErr_NewException("Comar.DBus", NULL, NULL);
    PyExc_PolicyKit = PyErr_NewException("Comar.PolicyKit", NULL, NULL);

    // Load model definitions
    PyObject *py_models;
    if (db_load_models(&py_models) != 0) {
        return -1;
    }

    if (PyDict_Size(py_models) == 0) {
        log_error("No models present in data/models directory.\n");
        return -1;
    }

    // Build core dictionary
    py_core = PyDict_New();
    PyDict_SetItemString(py_core, "models", py_models);
    PyDict_SetItemString(py_core, "locales", PyDict_New());

    log_debug("Models defined             : %d\n", PyDict_Size(py_models));
    log_debug("\n");

    return 0;
}
Beispiel #9
0
bool EmbedPython::init()
{

    if(initialized)
        return true;

    /** Setting Python folder */
    QDir dir(qApp->applicationDirPath());
    //
    QString p = QString("python27");
    py_progname = p.toLocal8Bit();

#if __APPLE__
    dir.cdUp();
    dir.cd("Resources");
    dir.cd("site-packages");
#endif

    p = dir.absolutePath();// + dir.separator() + QString("embed");

    py_pythonhome = p.toLocal8Bit();
    //QMessageBox::warning(NULL, "", p);

#if !__APPLE__
    Py_SetProgramName(py_progname.data());
//    qDebug()<<"program path:"<<Py_GetProgramFullPath();
//    qDebug()<<"program name:"<<Py_GetProgramName();
//    qDebug()<<"python path:"<<Py_GetPath() ;
    Py_SetPythonHome(py_pythonhome.data());
#endif
//    qDebug()<<"program home:"<<Py_GetPythonHome();
//    qDebug()<<"program path:"<<Py_GetProgramFullPath();
//    qDebug()<<"program name:"<<Py_GetProgramName();
//    qDebug()<<"python path:"<<Py_GetPath() ;
//    QMessageBox::warning(NULL, "", Py_GetPath());
    /** Initialize Python */
    Py_InitializeEx(0);
    //Py_Initialize();
    if(Py_IsInitialized() != 0) {
        initialized = true;
        //globals = PyList_New(0);
        //locals = PyList_New(0);
//        PyObject* fromlist = PyList_New(1);
//        PyList_SET_ITEM(fromlist, 0, PyString_FromString("*"));
        /** Import main module */
//        char mname[512];
//        memset(mname, 0, 512);
//        memcpy(mname, "__main__", sizeof("__main__"));
//        mainmodel = PyImport_ImportModuleEx(mname, globals, locals, fromlist);
//        checkError();
        /** Import modeltool module */
//        memset(mname, 0, 512);
//        memcpy(mname, MODELTOOL, sizeof(MODELTOOL));
        //modeltool = PyImport_ImportModuleEx(mname, globals, locals, fromlist);
        QString cmd = QString("import sys; import os;  sys.path.append(os.path.abspath('%1'))")
#if __APPLE__
                .arg(dir.absolutePath());
#else
                .arg(qApp->applicationDirPath());
Beispiel #10
0
void initialize()
{
    if(!Py_IsInitialized())
    {
        Py_InitializeEx(0); // 0 -> do not handle signals
        SLM_ASSERT( "python initialization failed ", isInitialized() );
    }
}
Beispiel #11
0
void PythonModule::subscribe() {
    if(subscribers==0) {
        // Initialize Python without signal handlers
        Py_InitializeEx(1);
        PyEval_InitThreads();
        unblock_threads();
    }
    subscribers++;
}
void ModuleLoader::init()
{
	Py_InitializeEx(0);
	PyEval_InitThreads();	//note, this implicitly acquires the lock!

	g_pymaintstate = PyThreadState_Get();

	PyEval_ReleaseLock();
}
Beispiel #13
0
PyObject*
ada_py_initialize_and_module(char* program_name, char* name) {
   PyObject* module;
   PyObject* imported;

   user_module_name = strdup(name);

#if PY_MAJOR_VERSION >= 3
   user_module.m_name = user_module_name;
   Py_SetProgramName ((wchar_t*)program_name);
#else
   Py_SetProgramName (program_name);
#endif

   PyImport_AppendInittab(user_module_name, init_user_module);
   Py_InitializeEx(0);

   // Initialize the prompt if needed

   PyObject* prompt = PySys_GetObject ("ps1");
   if (prompt == NULL) {
      prompt = PyUnicode_FromString (">>> ");
      PySys_SetObject ("ps1", prompt);
      Py_DECREF (prompt);
   }

   prompt = PySys_GetObject ("ps2");
   if (prompt == NULL) {
      prompt = PyUnicode_FromString ("... ");
      PySys_SetObject ("ps2", prompt);
      Py_DECREF (prompt);
   }

   // Make the user's module visible to scripts. We cannot use
   // PyImport_ImportModule, which imports the module but doesn't add
   // it to the global dictionary and as such it is not visible to
   // user scripts.

   imported = PyImport_ImportModule(name);
   if (imported == NULL) {
      printf ("Could not import module %s", name);
      return NULL;
   }

   // Import 'sys', which is needed for instance in Set_Default_Console
   // to get access to the default value
   PyRun_SimpleString("import sys\n");

   char* command = (char*)malloc(9 + strlen(name));
   strcpy (command, "import ");
   strcat (command, name);
   strcat (command, "\n");
   PyRun_SimpleString(command);
   free (command);

   return imported;
};
static
void init_python(void)
{
	PyObject *py_bt2_py_plugin_mod = NULL;
	const char *dis_python_env;
	sighandler_t old_sigint = signal(SIGINT, SIG_DFL);

	if (python_state != PYTHON_STATE_NOT_INITED) {
		goto end;
	}

	/*
	 * User can disable Python plugin support with the
	 * BABELTRACE_DISABLE_PYTHON_PLUGINS environment variable set to
	 * 1.
	 */
	dis_python_env = getenv("BABELTRACE_DISABLE_PYTHON_PLUGINS");
	if (dis_python_env && strcmp(dis_python_env, "1") == 0) {
		BT_LOGI_STR("Python plugin support is disabled because `BABELTRACE_DISABLE_PYTHON_PLUGINS=1`.");
		python_state = PYTHON_STATE_CANNOT_INITIALIZE;
		goto end;
	}

	if (!Py_IsInitialized()) {
		Py_InitializeEx(0);
		BT_LOGI("Initialized Python interpreter: version=\"%s\"",
			Py_GetVersion());
	}

	py_bt2_py_plugin_mod = PyImport_ImportModule("bt2.py_plugin");
	if (!py_bt2_py_plugin_mod) {
		BT_LOGI_STR("Cannot import bt2.py_plugin Python module: Python plugin support is disabled.");
		python_state = PYTHON_STATE_CANNOT_INITIALIZE;
		goto end;
	}

	py_try_load_plugin_module_func =
		PyObject_GetAttrString(py_bt2_py_plugin_mod, "_try_load_plugin_module");
	if (!py_try_load_plugin_module_func) {
		BT_LOGI_STR("Cannot get _try_load_plugin_module attribute from bt2.py_plugin Python module: Python plugin support is disabled.");
		python_state = PYTHON_STATE_CANNOT_INITIALIZE;
		goto end;
	}

	python_state = PYTHON_STATE_FULLY_INITIALIZED;

end:
	if (old_sigint != SIG_ERR) {
		(void) signal(SIGINT, old_sigint);
	}

	print_python_traceback_warn();
	pyerr_clear();
	Py_XDECREF(py_bt2_py_plugin_mod);
	return;
}
Beispiel #15
0
void PythonModule::initialize() throw (VoreenException) {
    VoreenModule::initialize();

    //
    // Initialize Python interpreter
    //
    LINFO("Python version: " << Py_GetVersion());

    // Pass program name to the Python interpreter
    char str_pyvoreen[] = "PyVoreen";
    Py_SetProgramName(str_pyvoreen);

    // Initialize the Python interpreter. Required.
    Py_InitializeEx(false);
    if (!Py_IsInitialized())
        throw VoreenException("Failed to initialize Python interpreter");

    // required in order to use threads.
    PyEval_InitThreads();

    // init ResourceManager search path
    addPath("");
    addPath(VoreenApplication::app()->getScriptPath());
    addPath(VoreenApplication::app()->getModulePath("python/scripts"));

    // init Python's internal module search path
    addModulePath(VoreenApplication::app()->getScriptPath());
    addModulePath(VoreenApplication::app()->getModulePath("python/scripts"));

    //
    // Redirect script output from std::cout to voreen_print function (see above)
    //

    // import helper module
    if (!Py_InitModule("voreen_internal", internal_methods)) {
        LWARNING("Failed to init helper module 'voreen_internal'");
    }

    // load output redirector script and run it once
    std::string filename = "outputcatcher.py";
    LDEBUG("Loading Python init script '" << filename << "'");
    PythonScript* initScript = load(filename);
    if (initScript) {
        if (!initScript->run())
            LWARNING("Failed to run init script '" << filename << "': " << initScript->getLog());
        dispose(initScript);
    }
    else {
        LWARNING("Failed to load init script '" << filename << "'");
    }

    //
    // Create actual Voreen Python bindings
    //
    pyVoreen_ = new PyVoreen();
}
Beispiel #16
0
void python_init() {
	if (not Py_IsInitialized()) {
		//register signal handlers (kill, term, ...) to python?
		constexpr int init_signals = 1;
		Py_InitializeEx(init_signals);

		const char *py_version = Py_GetVersion();
		log::msg("initialized python %s", py_version);
	}
}
 python_persistency() 
 {
    // changed to skip installation of signal handlers [PS]
    //
    Py_InitializeEx(0);
    // Py_Initialize();
    //
    char string_main[]="__main__";
    boost::python::object main_module((boost::python::handle<>(boost::python::borrowed(PyImport_AddModule(string_main)))));
    main_namespace = main_module.attr("__dict__");
 };
Beispiel #18
0
static void
python_init (void)
{
  if (Py_IsInitialized ())
    return;

  Py_InitializeEx (0);

  /* if argc is 0 an empty string is prepended to sys.path */
  PySys_SetArgvEx (0, NULL, 0);
}
Beispiel #19
0
static int python_init(void)
{
  if (initialized) return TCL_OK;
  DEBUG_TCL_TURBINE("python: initializing...");
  Py_InitializeEx(1);
  main_module  = PyImport_AddModule("__main__");
  if (main_module == NULL) return handle_python_exception();
  main_dict = PyModule_GetDict(main_module);
  if (main_dict == NULL) return handle_python_exception();
  initialized = true;
  return TCL_OK;
}
Beispiel #20
0
		void PyManager::initialize(const wchar_t *wszProgram, int siginit)
		{
			if (!Py_IsInitialized())
			{
				if(g_program)
					Py_SetProgramName(const_cast<decltype(g_program)>(wszProgram));
				Py_InitializeEx(siginit);

				// Create default events
				createEvent("register_event");					// Triggered when someone registers handler for an event
			}
		}
Beispiel #21
0
static void real_init(void) {
#ifdef VS_TARGET_OS_WINDOWS
    // portable
    const std::wstring pythonDllName = L"python37.dll";
    HMODULE module;
    GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, (LPCWSTR)&real_init, &module);
    std::vector<wchar_t> pathBuf(65536);
    GetModuleFileNameW(module, pathBuf.data(), (DWORD)pathBuf.size());
    std::wstring dllPath = pathBuf.data();
    dllPath.resize(dllPath.find_last_of('\\') + 1);
    std::wstring portableFilePath = dllPath + L"portable.vs";
    FILE *portableFile = _wfopen(portableFilePath.c_str(), L"rb");
    bool isPortable = !!portableFile;
    if (portableFile)
        fclose(portableFile);

    HMODULE pythonDll = nullptr;

    if (isPortable) {
        std::wstring pyPath = dllPath + L"\\" + pythonDllName;
        pythonDll = LoadLibraryExW(pyPath.c_str(), nullptr, LOAD_LIBRARY_SEARCH_DEFAULT_DIRS | LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR);
    } else {
        DWORD dwType = REG_SZ;
        HKEY hKey = 0;

        wchar_t value[1024];
        DWORD valueLength = 1000;
        if (RegOpenKeyW(HKEY_LOCAL_MACHINE, L"SOFTWARE\\VapourSynth", &hKey) != ERROR_SUCCESS)
            return;
        LSTATUS status = RegQueryValueExW(hKey, L"PythonPath", nullptr, &dwType, (LPBYTE)&value, &valueLength);
        RegCloseKey(hKey);
        if (status != ERROR_SUCCESS)
            return;

        std::wstring pyPath = value;
        pyPath += L"\\" + pythonDllName;

        pythonDll = LoadLibraryExW(pyPath.c_str(), nullptr, LOAD_LIBRARY_SEARCH_DEFAULT_DIRS | LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR);
    }
    if (!pythonDll)
        return;
#endif
    int preInitialized = Py_IsInitialized();
    if (!preInitialized)
        Py_InitializeEx(0);
    s = PyGILState_Ensure();
    if (import_vapoursynth())
        return;
    if (vpy_initVSScript())
        return;
    ts = PyEval_SaveThread();
    initialized = true;
}
Beispiel #22
0
static int mod_init(rlm_python_t *inst)
{
	int i;
	static char name[] = "radiusd";

	if (radiusd_module) return 0;

	Py_SetProgramName(name);
#ifdef HAVE_PTHREAD_H
	Py_InitializeEx(0);				/* Don't override signal handlers */
	PyEval_InitThreads(); 				/* This also grabs a lock */
	inst->main_thread_state = PyThreadState_Get();	/* We need this for setting up thread local stuff */
#endif
	if (inst->python_path) {
		PySys_SetPath(inst->python_path);
	}
	
	if ((radiusd_module = Py_InitModule3("radiusd", radiusd_methods,
					     "FreeRADIUS Module.")) == NULL)
		goto failed;

	for (i = 0; radiusd_constants[i].name; i++) {
		if ((PyModule_AddIntConstant(radiusd_module, radiusd_constants[i].name,
					     radiusd_constants[i].value)) < 0) {
			goto failed;
		}
	}

#ifdef HAVE_PTHREAD_H
	PyThreadState_Swap(NULL);	/* We have to swap out the current thread else we get deadlocks */
	PyEval_ReleaseLock();		/* Drop lock grabbed by InitThreads */
#endif
	DEBUG("mod_init done");
	return 0;

failed:
	Py_XDECREF(radiusd_module);

#ifdef HAVE_PTHREAD_H
	PyEval_ReleaseLock();
#endif

	Pyx_BLOCK_THREADS
	mod_error();
	Pyx_UNBLOCK_THREADS

	radiusd_module = NULL;

	Py_Finalize();
	return -1;
}
VS_API(int) vseval_init(void) {
	if (initializationCount == 0) {
		preInitialized = Py_IsInitialized();
		if (!preInitialized)
			Py_InitializeEx(0);
		PyGILState_STATE s = PyGILState_Ensure();
		int result = import_vapoursynth();
		if (result)
			return 0;
		vpy_initVSScript();
		ts = PyEval_SaveThread();
	}
	initializationCount++;
    return initializationCount;
}
Beispiel #24
0
    PythonEngine( wchar_t *pypath )
	    : m_global_dict( nullptr )
    {
		assert__( pypath );

        Py_SetPythonHome( pypath );

        Py_InitializeEx( 0 );

        // Get a reference to the main module and global dictionary
        //
        PyObject *main_module = PyImport_AddModule("__main__");
        if (main_module)
            m_global_dict = PyModule_GetDict( main_module );
    }
Beispiel #25
0
static void _cffi_py_initialize(void)
{
    /* XXX use initsigs=0, which "skips initialization registration of
       signal handlers, which might be useful when Python is
       embedded" according to the Python docs.  But review and think
       if it should be a user-controllable setting.

       XXX we should also give a way to write errors to a buffer
       instead of to stderr.

       XXX if importing 'site' fails, CPython (any version) calls
       exit().  Should we try to work around this behavior here?
    */
    Py_InitializeEx(0);
}
Beispiel #26
0
/*@C
  PetscPythonInitialize - Initialize Python and import petsc4py.

   Input Parameter:
+  pyexe - path to the Python interpreter executable, or PETSC_NULL.
-  pylib - full path to the Python dynamic library, or PETSC_NULL.

  Level: intermediate

.keywords: Python
  
@*/
PetscErrorCode PETSC_DLLEXPORT PetscPythonInitialize(const char pyexe[],const char pylib[])
{
  int               argc       = 0;
  char              **argv     = 0;
  PyObject          *module    = 0;
  static PetscTruth registered = PETSC_FALSE;
  PetscErrorCode    ierr;
  PetscFunctionBegin;
  if (PetscBeganPython) PetscFunctionReturn(0);
  /* Python executable */
  if (pyexe && pyexe[0] != 0) {
    ierr = PetscStrncpy(PetscPythonExe,pyexe,sizeof(PetscPythonExe));CHKERRQ(ierr);
  } else {
    ierr = PetscPythonFindExecutable(PetscPythonExe);CHKERRQ(ierr);
  }
  /* Python dynamic library */
  if (pylib && pylib[0] != 0) {
    ierr = PetscStrncpy(PetscPythonLib,pylib,sizeof(PetscPythonLib));CHKERRQ(ierr);
  } else {
    ierr = PetscPythonFindLibrary(PetscPythonExe,PetscPythonLib);CHKERRQ(ierr);
  }
  /* dynamically load Python library */
  ierr = PetscPythonLoadLibrary(PetscPythonLib);CHKERRQ(ierr);
  /* initialize Python */
  PetscBeganPython = PETSC_FALSE;
  if (!Py_IsInitialized()) {
    /* call below does not install signal handlers */
    Py_InitializeEx(0);
    /* call below required to build 'sys.argv' list */
    ierr = PetscGetArgs(&argc,&argv);CHKERRQ(ierr);
    if (argc && argv && argv[0]) PySys_SetArgv(argc,argv);
    /* register finalizer */
    if (!registered) {
      ierr = PetscRegisterFinalize(PetscPythonFinalize);CHKERRQ(ierr);
      registered = PETSC_TRUE;
    }
    PetscBeganPython = PETSC_TRUE;
  }
  /* import 'petsc4py.PETSc' module */
  module = PyImport_ImportModule("petsc4py.PETSc");
  if (module) {
    ierr = PetscInfo(0,"Python: successfully imported  module 'petsc4py.PETSc'\n");CHKERRQ(ierr);
    Py_DecRef(module); module = 0;
  } else {
    SETERRQ(PETSC_ERR_PLIB,"Python: could not import module 'petsc4py.PETSc', perhaps your PYTHONPATH does not contain it\n"); 
  }
  PetscFunctionReturn(0);
}
Beispiel #27
0
mraa_init()
{
    /** Once more board definitions have been added,
     *  A method for detecting them will need to be devised.
     */
    if (plat != NULL) {
        return MRAA_ERROR_PLATFORM_ALREADY_INITIALISED;
    }
#ifdef SWIGPYTHON
    // Initialise python threads, this allows use to grab the GIL when we are
    // required to do so
    Py_InitializeEx(0);
    PyEval_InitThreads();
#endif
    // detect a galileo gen2 board
    char *line = NULL;
    // let getline allocate memory for *line
    size_t len = 0;
    FILE *fh = fopen("/sys/devices/virtual/dmi/id/board_name", "r");
    if (fh != NULL) {
        if (getline(&line, &len, fh) != -1) {
            if (strncmp(line, "GalileoGen2", 10) == 0) {
                platform_type = MRAA_INTEL_GALILEO_GEN2;
            } else {
                platform_type = MRAA_INTEL_GALILEO_GEN1;
            }
            free(line);
        }
        fclose(fh);
    }

    advance_func = (mraa_adv_func_t*) malloc(sizeof(mraa_adv_func_t));
    memset(advance_func, 0, sizeof(mraa_adv_func_t));

    switch(platform_type) {
        case MRAA_INTEL_GALILEO_GEN2:
            plat = mraa_intel_galileo_gen2();
            break;
        case MRAA_INTEL_GALILEO_GEN1:
            plat = mraa_intel_galileo_rev_d();
            break;
        default:
            plat = mraa_intel_galileo_rev_d();
            fprintf(stderr, "Platform not found, initialising MRAA_INTEL_GALILEO_GEN1\n");
    }

    return MRAA_SUCCESS;
}
Beispiel #28
0
/// initializes the python bridge
/// only does the initialization on the first call, subsequent calls are ignored
static void initPythonBridgeOnce()
{
    static bool alreadyInitialized = false;
    if( alreadyInitialized) return;
    alreadyInitialized = true;

    dlopen("libpython2.7.so", RTLD_LAZY | RTLD_GLOBAL);

    Py_InitializeEx( 0); // make ctrl-c work?

    // try to enable ctrl-c...
    enableCtrlC();

    // call cython generated code (pluginBridge.pyx)
    initpluginBridge();
}
Beispiel #29
0
mraa_init()
{
    if (plat != NULL) {
        return MRAA_ERROR_PLATFORM_ALREADY_INITIALISED;
    }

    uid_t proc_euid = geteuid();
    struct passwd* proc_user = getpwuid(proc_euid);

#ifdef DEBUG
    setlogmask(LOG_UPTO(LOG_DEBUG));
#else
    setlogmask(LOG_UPTO(LOG_NOTICE));
#endif

    openlog("libmraa", LOG_CONS | LOG_PID | LOG_NDELAY, LOG_LOCAL1);
    syslog(LOG_NOTICE, "libmraa version %s initialised by user '%s' with EUID %d",
           mraa_get_version(), (proc_user != NULL) ? proc_user->pw_name : "<unknown>", proc_euid);

#ifdef SWIGPYTHON
    // Initialise python threads, this allows use to grab the GIL when we are
    // required to do so
    Py_InitializeEx(0);
    PyEval_InitThreads();
#endif
    advance_func = (mraa_adv_func_t*) malloc(sizeof(mraa_adv_func_t));
    memset(advance_func, 0, sizeof(mraa_adv_func_t));

#if defined(X86PLAT)
    // Use runtime x86 platform detection
    platform_type = mraa_x86_platform();
#elif defined(ARMPLAT)
    // Use runtime ARM platform detection
    platform_type = mraa_arm_platform();
#else
#error mraa_ARCH NOTHING
#endif

    if (plat == NULL) {
        printf("mraa: FATAL error, failed to initialise platform\n");
        return MRAA_ERROR_PLATFORM_NOT_INITIALISED;
    }

    syslog(LOG_INFO, "libmraa initialised for platform '%s' of type %d", mraa_get_platform_name(), platform_type);
    return MRAA_SUCCESS;
}
Beispiel #30
0
void
cu5_pennpy_initialize(void)
{
    FILE *main_py_fp;

    assert(cu5_pennpy_main == NULL);

    do_rawlog(LT_ERR, T("PennPy: Initializing"));

    /* Initialize Python without installing signal handlers. */
    Py_InitializeEx(0);

    /* Borrow a reference to __main__. */
    if (!(cu5_pennpy_main = PyImport_AddModule("__main__"))) {
        /* This shouldn't happen, but you never know. */
        mush_panic(T("PennPy: Can't get reference to __main__"));
    }

    cu5_pennpy_main_dict = PyModule_GetDict(cu5_pennpy_main);

    /* Initialize __pennmush__ internal module. */
    if (!cu5_pennpy_initialize_module()) {
        /* Can't initialize module. */
        mush_panic(T("PennPy: Can't initialize __pennmush__ module"));
    }

    /* Execute game/python/main.py. */
    if (!(main_py_fp = fopen(MAIN_PY, "r"))) {
        /* Can't run main.py. */
        do_rawlog(LT_ERR, T("PennPy: Can't open %s"), MAIN_PY);
        return;
    }

    if (PyRun_SimpleFile(main_py_fp, MAIN_PY) != 0) {
        /* Something wrong with main.py. */
        do_rawlog(LT_ERR, T("PennPy: Failed to execute %s"), MAIN_PY);
        fclose(main_py_fp);
        return;
    }

    fclose(main_py_fp);

    /* Ready. */
    cu5_pennpy_enabled = 1;
}