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; };
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); }
void do_pyinit() { #ifdef EXPOSE_PERL PyObject *main_dict; PyObject *perl_obj; PyObject *dummy1 = PyString_FromString(""), *dummy2 = PyString_FromString("main"); #endif /* sometimes Python needs to know about argc and argv to be happy */ int _python_argc = 1; char *_python_argv[] = { "python", }; Py_SetProgramName("python"); Py_Initialize(); PySys_SetArgv(_python_argc, _python_argv); /* Tk needs this */ #ifdef EXPOSE_PERL /* create the perl module and add functions */ initperl(); /* now -- create the main 'perl' object and add it to the dictionary. */ perl_obj = newPerlPkg_object(dummy1,dummy2); main_dict = PyModule_GetDict(PyImport_AddModule("__main__")); PyDict_SetItemString(main_dict, "perl", perl_obj); Py_DECREF(perl_obj); Py_DECREF(dummy1); Py_DECREF(dummy2); #endif }
void PythonRunner::initPython() { XOJ_CHECK_TYPE(PythonRunner); if (this->pythonInitialized) { return; } Py_SetProgramName("Xournal"); Py_Initialize(); PyXournal_initPython(this->control); char buffer[512] = { 0 }; const char * path = getcwd(buffer, sizeof(buffer)); g_return_if_fail(path != NULL); PyObject * sysModule = PyImport_ImportModule("sys"); g_return_if_fail(sysModule != NULL); PyObject * pathObject = PyObject_GetAttrString(sysModule, "path"); g_return_if_fail(pathObject != NULL); String p = path; p += "/../testing"; PyObject * ret = PyObject_CallMethod(pathObject, "append", "s", p.c_str()); Py_DecRef(ret); p = path; p += "/testing"; ret = PyObject_CallMethod(pathObject, "append", "s", p.c_str()); Py_DecRef(ret); Py_DecRef(pathObject); Py_DecRef(sysModule); }
void embed_init_python(void) { FENTER; #ifndef PYTHON_SO_LIB #error "Python version needs passing in with -DPYTHON_SO_VERSION=libpython<ver>.so" #else #define PY_SO_LIB xstr(PYTHON_SO_LIB) #endif void *ret = dlopen(PY_SO_LIB, RTLD_LAZY | RTLD_GLOBAL); if (!ret) { fprintf(stderr, "Failed to find python lib %s (%s)\n", PY_SO_LIB, dlerror()); } // Don't initialise python if already running if (gtstate) return; Py_SetProgramName(progname); Py_Initialize(); /* Initialize the interpreter */ PySys_SetArgvEx(1, argv, 0); PyEval_InitThreads(); /* Create (and acquire) the interpreter lock */ /* Swap out and return current thread state and release the GIL */ gtstate = PyEval_SaveThread(); FEXIT; }
static void _testembed_Py_Initialize(void) { /* HACK: the "./" at front avoids a search along the PATH in Modules/getpath.c */ Py_SetProgramName(L"./_testembed"); Py_Initialize(); }
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; }
int main(int argc, char *argv[]) { Py_SetProgramName(argv[0]); Py_Initialize(); initschoolboy_rsa(); return 0; }
Pyramid::Pyramid(const char* script) { freopen("pyramid.log", "w", stdout); freopen("pyramid.log", "a", stderr); Py_SetProgramName(".\\pyramid"); Py_Initialize(); init_pyramid(); PyRun_SimpleString( "import sys\n" "sys.path.append('./')\n" "sys.stderr = open('python_errors.log', 'w', 0)\n" "sys.stdout = open('pyramid.log', 'a', 0)\n" "import pyramid\n"); char* fn_local = new char[strlen(script)+1]; strcpy(fn_local, script); PyObject* fp = PyFile_FromString(fn_local, "r"); if(!fp) { printf("Could not load mapping script '%s' for reading.\n", script); Py_Finalize(); exit(1); } FILE* sfp = PyFile_AsFile(fp); PyRun_AnyFileEx(sfp, script, 1); delete[] fn_local; }
/* 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); } } } }
rpmpython rpmpythonNew(char ** av, uint32_t flags) { static char * _av[] = { "rpmpython", NULL }; #if defined(WITH_PYTHONEMBED) int initialize = (!(flags & 0x80000000) || _rpmpythonI == NULL); #endif rpmpython python = (flags & 0x80000000) ? rpmpythonI() : rpmpythonGetPool(_rpmpythonPool); if (_rpmpython_debug) fprintf(stderr, "==> %s(%p, %d) python %p\n", __FUNCTION__, av, flags, python); if (av == NULL) av = _av; #if defined(WITH_PYTHONEMBED) if (!Py_IsInitialized()) { Py_SetProgramName((char *)_av[0]); Py_Initialize(); } if (PycStringIO == NULL) PycStringIO = PyCObject_Import("cStringIO", "cStringIO_CAPI"); if (initialize) { int ac = argvCount((ARGV_t)av); (void) PySys_SetArgv(ac, (char **)av); (void) rpmpythonRun(python, rpmpythonInitStringIO, NULL); } #endif return rpmpythonLink(python); }
int main(int argc, char **argv) { #if (COW_MPI) { int rank; MPI_Init(&argc, &argv); MPI_Comm_rank(MPI_COMM_WORLD, &rank); if (rank != 0) freopen("/dev/null", "w", stdout); printf("was compiled with MPI support\n"); } #endif Py_Initialize(); PySys_SetArgv(argc, argv); Py_SetProgramName("/Users/jzrake/Work/cow/cowpy"); init_cow(); if (argc > 1) { FILE *fp = fopen(argv[1], "r"); if (fp) { PyRun_SimpleFileExFlags(fp, argv[1], 1, NULL); fclose(fp); } else { printf("No such file %s\n", argv[1]); } } Py_Finalize(); printf("finished...\n"); #if (COW_MPI) MPI_Finalize(); #endif return 0; }
int main(int argc, char *argv[]) { Py_SetProgramName(argv[0]); Py_Initialize(); initbwdithering(); return 0; }
int main(int argc, char *argv[]) { // Set the python interpreter. setup_python(argc, argv); std::string filepath(argv[0]); // Get the path to the helper script. std::string helper_path; size_t path_end = filepath.find_last_of('\\'); if (path_end != std::string::npos) helper_path = filepath.substr(0, path_end + 1); helper_path += "wbadminhelper.py"; // Configures the execution of the script to take the same // parameters as this helper tool. Py_SetProgramName(argv[0]); PySys_SetArgv(argc, argv); // Executes the helper script. PyObject *pFileObject = PyFile_FromString(const_cast<char *>(helper_path.c_str()), "r"); PyRun_SimpleFileEx(PyFile_AsFile(pFileObject), "wbadminhelper.py", 1); finalize_python(); return 0; }
int main(int argc, char **argv) { PyObject *main, *game; PyObject *func, *args; PyTaskletObject *process; Py_SetProgramName(argv[0]); Py_Initialize(); /* get the time python methods */ timemod = PyImport_ImportModule("time"); /* create a module for the game */ game = Py_InitModule("game", game_methods); /* run the definition in main module */ main = PyImport_AddModule("__main__"); PyRun_SimpleString(python_prog); /* runs in main */ /* start the python function as a tasklet */ func = PyObject_GetAttrString(main, "everySecond"); process = PyTasklet_New(NULL, func); Py_DECREF(func); /* initialize the tasklet args */ args = PyTuple_New(0); PyTasklet_Setup(process, args, NULL); Py_DECREF(args); /* now let's run the "game engine" */ run_game_engine(); Py_Finalize(); return 0; }
int main(int argc, char *argv[]) { Py_SetProgramName(argv[0]); Py_Initialize(); initacc_monitor(); return 1; }
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(); }
int main(int argc, char *argv[]) { Py_SetProgramName(argv[0]); Py_Initialize(); initfirstmodule(); }
int main(int argc, char *argv[]) { int ret = 0; /* Must be the first thing we do to get everything else started * We can do this here even though Py_Main will call those again. * However, we must run them before creating our sub-interpreter. * * See comments on ARGV0 as to why we set it like this. */ Py_SetProgramName(ARGV0); Py_Initialize(); /* Create sub-interpreter */ #ifdef DEBUG fprintf(stderr, "starting new interpreter\n"); #endif shd_py_interpreter = Py_NewInterpreter(); if(!shd_py_interpreter) { PyErr_Print(); return 1; } PyThreadState *old = PyThreadState_Swap(shd_py_interpreter); ret = python_main(argc, argv); #ifdef DEBUG fprintf(stderr, "shutting down interpreter\n"); #endif PyThreadState_Swap(shd_py_interpreter); Py_EndInterpreter(shd_py_interpreter); shd_py_interpreter = NULL; PyThreadState_Swap(old); Py_Finalize(); return ret; #undef PYERR }
/** This imports a Python module and calls a specific function in it. * It's arguments are similar to main(): * argc - Number of strings in argv * argv - Expected to be 4 strings: * - Name of the executable. * - Path to the directory that the Python module is in. * - Name of the Python module. * - Name of the function in the module. * * The Python interpreter will be initialised and the path to the Python module * will be added to sys.paths then the module will be imported. * The function will be called with no arguments and its return value will be * ignored. * * This returns 0 on success, non-zero on failure. */ int import_call_execute(int argc, const char *argv[]) { int return_value = 0; PyObject *pModule = NULL; PyObject *pFunc = NULL; PyObject *pResult = NULL; if (argc != 4) { fprintf(stderr, "Wrong arguments!" " Usage: %s package_path module function\n", argv[0]); return_value = -1; goto except; } Py_SetProgramName((wchar_t*)argv[0]); Py_Initialize(); if (add_path_to_sys_module(argv[1])) { return_value = -2; goto except; } pModule = PyImport_ImportModule(argv[2]); if (! pModule) { fprintf(stderr, "%s: Failed to load module \"%s\"\n", argv[0], argv[2]); return_value = -3; goto except; } pFunc = PyObject_GetAttrString(pModule, argv[3]); if (! pFunc) { fprintf(stderr, "%s: Can not find function \"%s\"\n", argv[0], argv[3]); return_value = -4; goto except; } if (! PyCallable_Check(pFunc)) { fprintf(stderr, "%s: Function \"%s\" is not callable\n", argv[0], argv[3]); return_value = -5; goto except; } pResult = PyObject_CallObject(pFunc, NULL); if (! pResult) { fprintf(stderr, "%s: Function call failed\n", argv[0]); return_value = -6; goto except; } #ifdef DEBUG printf("%s: PyObject_CallObject() succeeded\n", argv[0]); #endif assert(! PyErr_Occurred()); goto finally; except: assert(PyErr_Occurred()); PyErr_Print(); finally: Py_XDECREF(pFunc); Py_XDECREF(pModule); Py_XDECREF(pResult); Py_Finalize(); return return_value; }
int main(int argc, char *argv[]) { Py_SetProgramName(argv[0]); Py_Initialize(); initscsi(); }
/* Initialize Python interpreter */ static void python_system_init(lua_State *L) { char *python_home = luaL_check_string(L, 1); if (!Py_IsInitialized()) { PyObject *luam, *mainm, *maind; #if PY_MAJOR_VERSION >= 3 wchar_t *argv[] = {L"<lua>", 0}; #else char *argv[] = {"<lua>", 0}; #endif Py_SetProgramName(argv[0]); Py_SetPythonHome(python_home); Py_Initialize(); PySys_SetArgv(1, argv); /* Import 'lua' automatically. */ luam = PyImport_ImportModule("lua"); if (!luam) { lua_error(L, "Can't import lua 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", luam); Py_DECREF(luam); } } } }
static int mod_init(void) { int i; static char name[] = "radiusd"; if (radiusd_module) return 0; Py_SetProgramName(name); Py_Initialize(); PyEval_InitThreads(); /* This also grabs a lock */ 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; PyEval_ReleaseLock(); /* Drop lock grabbed by InitThreads */ DEBUG("mod_init done"); return 0; failed: mod_error(); Py_XDECREF(radiusd_module); radiusd_module = NULL; Py_Finalize(); return -1; }
int main(int argc, char **argv) { PyObject *gameModule, *utilModule, *func, *ret, *args; PyTaskletObject *tasklet; int i; Py_SetProgramName(argv[0]); Py_Initialize(); niceChannel = PyChannel_New(NULL); utilModule = Py_InitModule("util", util_methods); gameModule = PyImport_ImportModule("game"); if (gameModule == NULL) { CheckForErrors(); } /* Allow the startup script "game.py" to start some tasklets in its Run method. I initially tried calling it directly as a function but it seemed to be called twice. */ func = PyObject_GetAttrString(gameModule, "Run"); if (func == NULL) { CheckForErrors(); } tasklet = PyTasklet_New(NULL, func); Py_DECREF(func); PyTasklet_SetBlockTrap(tasklet, 1); args = PyTuple_New(0); PyTasklet_Setup(tasklet, args, NULL); Py_DECREF(args); PyTasklet_Run(tasklet); while (1) { for (i = niceChannel->balance; i < 0; i++) { PyChannel_Send(niceChannel, Py_None); CheckForErrors(); } do { ret = PyStackless_RunWatchdog(2000000); if (ret != NULL && ret != Py_None) { PyTasklet_Kill((PyTaskletObject *)ret); CheckForErrors(); } Py_XDECREF(ret); } while (!ret); CheckForErrors(); } Py_DECREF(utilModule); Py_DECREF(gameModule); Py_DECREF(niceChannel); Py_Finalize(); return 0; }
PyObject* getFileData(int argc, char *argv[]) { PyObject *BioModule = PyImport_ImportModule("Bio"); const char *filename, *filetype, *pycmdToRun; filename = (const char *)PyUnicode_DecodeFSDefault(argv[1]); filetype = (const char *)PyUnicode_DecodeFSDefault(argv[2]); std::string cmdToRun = "import Bio\nBio.SeqIO.parse("; cmdToRun = cmdToRun + filename + std::string(",") + filetype; pycmdToRun = cmdToRun.c_str(); wchar_t *program = Py_DecodeLocale(argv[0], NULL); if (program == NULL) { fprintf(stderr, "Fatal error: cannot decode argv[0]\n"); exit(1); } Py_SetProgramName(program); /* optional but recommended */ Py_Initialize(); PyObject* filedata; filedata = PyRun_String(pycmdToRun, 0, NULL, NULL); Py_DECREF(filename); Py_DECREF(filetype); Py_Finalize(); PyMem_RawFree(program); return filedata; }
int main(int argc, char *argv[]) { Py_SetProgramName(argv[0]); Py_Initialize(); init_noise(); return 0; }
PythonLoader::PythonLoader(QObject *parent) : QObject(parent) { if (!Py_IsInitialized()) { QString sysPath = QCoreApplication::applicationDirPath(); QString programPath = sysPath + "/thirdparty/Python/bin/python3"; wchar_t* programName = new wchar_t[programPath.length() + 1]; programPath.toWCharArray(programName); programName[programPath.length()] = 0; Py_SetProgramName(programName); wprintf(L"python prefix path: %S\n", Py_GetPrefix()); wprintf(L"python full path: %S\n", Py_GetProgramFullPath()); Py_Initialize(); QStringList paths = {sysPath+"/thirdparty/Python/lib/python3.4", sysPath+"/thirdparty/Python/lib/python3.4/plat-linux", sysPath+"/thirdparty/Python/lib/python3.4/lib-dynload", sysPath+"/thirdparty/Python/lib/python3.4/site-packages", sysPath, sysPath+"/thirdparty/Python/lib", sysPath+"/thirdparty/Python/bin"}; QString wholePath = paths.join(":"); PySys_SetPath(wholePath.toStdWString().c_str()); getSipAPI(); PyEval_InitThreads(); PyEval_SaveThread(); } }
int main(int argc, char* argv[]) { assert(argc == 2); Py_SetProgramName(argv[0]); Py_Initialize(); init_extensions(); // initialize curses initscr(); // don't buffer user input into lines, // but Ctrl-Z and Ctrl-C work as usual cbreak(); // don't echo user input. noecho(); // getch returns ERR if the user takes more than a tenth of a second // halfdelay(1); // don't ignore function keys F1, F2, etc. keypad(stdscr, TRUE); // TODO: seed the random number generator with the time. PyRun_SimpleFile(fopen(argv[1], "r"), argv[1]); endwin(); Py_Finalize(); return 0; }
void InitAmigaPython(int argc, char **argv) { if(argc == 0) { /* Invoked from WorkBench... use WorkBench arguments */ /* Make sure <dos.h> was included earlier in order to */ /* declare _WBArgc and _WBArgv. */ argc = _WBArgc; argv = _WBArgv; from_WB = TRUE; } atexit(AmigaCleanup); /* cleanup func */ // setbuf(stderr,NULL); /* set error output UNBUFFERED */ orig_argc = argc; /* For Py_GetArgcArgv() */ orig_argv = argv; Py_SetProgramName(argv[0]); #ifdef AMITCP /** Sadly, this function cannot be called as a SAS/C standard **/ /** constructor function. It needs to have the interpreter **/ /** initialised because it uses the Python Error functions... **/ (void)_install_AmiTCP_callback(); #endif }
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; }