bool PythonEngine::RunFile(const std::string& path) { FILE* fp = fopen( path.c_str(), "r" ); if ( fp == NULL ) { Engine::out(Engine::ERROR) << "[PyScript] Error opening file: " << path << std::endl; return false; } int re = PyRun_SimpleFile( fp, path.c_str() ); fclose( fp ); return (re == 0); }
int ExecFile(char *FileName) { PyObject* PyFileObject = PyFile_FromString(FileName, "r"); if (!PyFileObject) { return 0; } if (PyRun_SimpleFile(PyFile_AsFile(PyFileObject), FileName) == 0) { Py_DECREF(PyFileObject); return 1; } else { Py_DECREF(PyFileObject); return 0; } }
void PythonEngine::RunScript(const QString &scriptname) { FILE *fp = fopen(scriptname.toAscii().data(), "r"); if (!fp) { PythonScriptModule::LogInfo("Failed to open script " + scriptname.toStdString()); return; } PyRun_SimpleFile(fp, scriptname.toAscii().data()); fclose(fp); }
void uwsgi_python_hijack(void) { // the pyshell will be execute only in the first worker #ifndef UWSGI_PYPY FILE *pyfile; if (up.pyrun) { uwsgi.workers[uwsgi.mywid].hijacked = 1; UWSGI_GET_GIL; pyfile = fopen(up.pyrun, "r"); if (!pyfile) { uwsgi_error_open(up.pyrun); exit(1); } PyRun_SimpleFile(pyfile, up.pyrun); // could be never executed exit(0); } #endif if (up.pyshell_oneshot && uwsgi.workers[uwsgi.mywid].hijacked_count > 0) { uwsgi.workers[uwsgi.mywid].hijacked = 0; return; } if (up.pyshell && uwsgi.mywid == 1) { uwsgi.workers[uwsgi.mywid].hijacked = 1; uwsgi.workers[uwsgi.mywid].hijacked_count++; // re-map stdin to stdout and stderr if we are logging to a file if (uwsgi.logfile) { if (dup2(0, 1) < 0) { uwsgi_error("dup2()"); } if (dup2(0, 2) < 0) { uwsgi_error("dup2()"); } } UWSGI_GET_GIL; PyImport_ImportModule("readline"); #ifndef UWSGI_PYPY int ret = PyRun_InteractiveLoop(stdin, "uwsgi"); if (up.pyshell_oneshot) { exit(UWSGI_DE_HIJACKED_CODE); } if (ret == 0) { exit(UWSGI_QUIET_CODE); } #endif exit(0); } }
int main(int argc, char* argv[]) { FILE* fp; fp = fopen(SCRIPT_NAME, "r"); Py_SetProgramName(argv[0]); Py_Initialize(); PyRun_SimpleFile(fp, SCRIPT_NAME); Py_Finalize(); return 0; }
/* * python_run() * * uruchamia jednorazowo skrypt pythona. * * 0/-1 */ int python_run(const char *filename, int quiet) { FILE *f = fopen(filename, "r"); if (!f) { printq("python_not_found", filename); return -1; } PyRun_SimpleFile(f, (char*) filename); fclose(f); return 0; }
/* * Start trace script */ static int python_start_script(const char *script, int argc, const char **argv) { const char **command_line; char buf[PATH_MAX]; int i, err = 0; FILE *fp; command_line = malloc((argc + 1) * sizeof(const char *)); command_line[0] = script; for (i = 1; i < argc + 1; i++) command_line[i] = argv[i - 1]; Py_Initialize(); initperf_trace_context(); PySys_SetArgv(argc + 1, (char **)command_line); fp = fopen(script, "r"); if (!fp) { sprintf(buf, "Can't open python script \"%s\"", script); perror(buf); err = -1; goto error; } err = PyRun_SimpleFile(fp, script); if (err) { fprintf(stderr, "Error running python script %s\n", script); goto error; } err = run_start_sub(); if (err) { fprintf(stderr, "Error starting python script %s\n", script); goto error; } free(command_line); fprintf(stderr, "perf trace started with Python script %s\n\n", script); return err; error: Py_Finalize(); free(command_line); return err; }
int main(int argc, char *argv[]) { int rv = 0; Py_Initialize(); if (0 != PyRun_SimpleFile(stdin, "stdin")) { rv = 1; } Py_Finalize(); return rv; }
void Effect::run() { // switch to the main thread state and acquire the GIL PyEval_RestoreThread(_mainThreadState); // Initialize a new thread state _interpreterThreadState = Py_NewInterpreter(); // import the buildtin Hyperion module PyObject * module = PyImport_ImportModule("hyperion"); // add a capsule containing 'this' to the module to be able to retrieve the effect from the callback function PyObject_SetAttrString(module, "__effectObj", PyCapsule_New(this, nullptr, nullptr)); // add ledCount variable to the interpreter PyObject_SetAttrString(module, "ledCount", Py_BuildValue("i", _imageProcessor->getLedCount())); // add a args variable to the interpreter PyObject_SetAttrString(module, "args", json2python(_args)); // decref the module Py_XDECREF(module); // Set the end time if applicable if (_timeout > 0) { _endTime = QDateTime::currentMSecsSinceEpoch() + _timeout; } // Run the effect script FILE* file = fopen(_script.c_str(), "r"); if (file != nullptr) { PyRun_SimpleFile(file, _script.c_str()); } else { std::cerr << "EFFECTENGINE ERROR: Unable to open script file " << _script << std::endl; } fclose(file); // Clean up the thread state Py_EndInterpreter(_interpreterThreadState); _interpreterThreadState = nullptr; PyEval_ReleaseLock(); }
int MPyEmbed_Run(char *file) { FILE *fp; if (!PythonAvailable) { return 0; } fp = fopen(file, "r"); if (!fp) { perror("fopen"); return 0; } mainstate->thread_id = PyThread_get_thread_ident(); PyEval_AcquireThread(mainstate); PyRun_SimpleFile(fp, file); PyEval_ReleaseThread(mainstate); fclose(fp); return 1; }
bool Pythonize::runScript (char *scriptPath) { FILE *f; int res; if (debug) printf ("Running script: %s\n", scriptPath); if (scriptPath == NULL || strlen (scriptPath) == 0) return false; f = fopen (scriptPath, "r"); if (f == NULL) return false; res = PyRun_SimpleFile (f, scriptPath); fclose (f); return res == 0; }
int main(int argc, char *argv[]) { setenv("PYTHONHOME", PYTHON_HOME, 1); setenv("PYTHONPATH", PYTHON_PATH, 1); setenv("LD_LIBRARY_PATH", LD_LIBRARY_PATH, 1); setenv("PATH", PATH, 1); QApplication app(argc, argv); Py_Initialize(); PySys_SetArgv(argc, argv); PySys_SetPath(PYTHON_PATH); FILE *fp = fopen(PYQT_MAIN, "r"); PyRun_SimpleFile(fp, PYQT_MAIN); fclose(fp); Py_Finalize(); //app.exec(); }
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; }
python_persistency(std::string file_name) { // 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__"); FILE* file = fopen(file_name.c_str(),"r"); if (file == 0) { std::cerr << "no file of name: " << file_name << std::endl; exit(-1); } PyRun_SimpleFile(file, file_name.c_str()); };
int main_thread(SceSize args, void *argp) { FILE *fp; int argc = 1; char *argv[] = {save_argv0}; #ifdef WITH_PSP2D sceGuInit(); #endif Py_Initialize(); PySys_SetPath("ms0:/python"); PySys_SetArgv(argc, argv); fp = fopen("script.py", "r"); if (fp) { PyRun_SimpleFile(fp, "script.py"); fclose(fp); } else { #ifndef DEBUG pspDebugScreenInit(); #endif pspDebugScreenPrintf("Error - could not open script.py\n"); } #ifdef DEBUG sceKernelDelayThreadCB(1e7); #endif Py_Finalize(); #ifdef WITH_PSP2D sceGuTerm(); #endif sceKernelExitGame(); return 0; }
/* Show python console */ void on_view_python_console_activate (GtkWidget *widget, gpointer user_data) { #ifdef USE_PYTHON FILE *console = fopen (GWP_SCRIPTS_DIR"/gtkcons.py", "r"); PyRun_SimpleFile(console, "gtkcons.py"); fclose (console); #else /* No Python support, warn the user */ GtkWidget *warn = gwp_warning_dialog_new (gwp, _("No Python support enabled."), _("If you need the Python scripting feature, you should recompile the program after installing Python development packages on your distribution.")); gtk_dialog_run(GTK_DIALOG(warn)); gtk_widget_destroy(warn); #endif }
static int shell_run_file(MYX_GRT *grt, const char *file_name, int interactive) { int status; int rc; FILE *f; MYX_GRT_SHELL_PRIVATE *pshell= grt->shell->data; if (interactive) myx_grt_printf(grt, "Opening script file %s ..."NL, file_name); f= fopen(file_name, "r"); if (!f) { if (interactive) myx_grt_printf(grt, "Error opening script file %s", strerror(errno)); return -1; } if (interactive) myx_grt_printf(grt, "Executing script file %s ..."NLNL, file_name); myx_py_acquire(pshell->pycon); status= PyRun_SimpleFile(f, file_name); myx_py_release(pshell->pycon); fclose(f); if (status) { myx_grt_printf(grt, "error executing script"NL); rc= -2; } else rc= 0; if ((rc == 0) && (interactive)) myx_grt_printf(grt, "\nExecution finished."NL); return rc; }
MainWindow::MainWindow(QWidget *parent, Qt::WindowFlags flags) : QMainWindow(parent, flags) { setObjectName("MainWindow"); setWindowTitle("cpp-qt-pyqt-py"); setupMenuBar(); // PyObject* PyRun_File(FILE *fp, const char *filename, int start, PyObject *globals, PyObject *locals) // FILE* file = fopen("test.py","r"); // PyRun_SimpleFile(file, "test.py"); PyObject *obj = Py_BuildValue("s", "test.py"); FILE *file = _Py_fopen_obj(obj, "r+"); if(file != NULL) { PyRun_SimpleFile(file, "../python/test.py"); } else { qDebug() << "file test.py not found (did you copy it in the build directory"; } }
// python.run function: run a python file from maxscript Value* run_cf( Value** arg_list, int count ) { // Step 1: make sure the arguments supplied are correct in count check_arg_count( python.run, 1, count ); // Step 2: protect the maxscript memory MXS_PROTECT(one_value_local(mxs_filename)); MXS_EVAL( arg_list[0], vl.mxs_filename ); // Step 2: create a python file based on the filename const MCHAR * filename = vl.mxs_filename->to_string(); //mprintf( _T("Got Filename to run: %s\n"), filename ); MCharToPyString pys(filename); PyObject* args = PyTuple_New(2); PyTuple_SET_ITEM(args,0,pys.pyStringRef()); PyTuple_SET_ITEM(args,1,PyString_FromString("r")); //mprintf( _T("Arg tuple created, creating python file object\n") ); PyObject* py_file = PyObject_Call((PyObject*)&PyFile_Type, args, NULL); Py_DECREF(args); if( !py_file ) { mprintf( _T("Call to python file object creation failed\n") ); PY_ERROR_PROPAGATE_MXS_CLEANUP(); return &false_value; } //mprintf( _T("File opened, calling PyRun_SimpleFile\n") ); // Step 4: run the file PyRun_SimpleFile( PyFile_AsFile(py_file), pys.data() ); //mprintf( _T("File ran, cleaning up\n") ); // Step 5: cleanup the memory Py_DECREF( py_file ); PY_ERROR_PROPAGATE_MXS_CLEANUP(); return &true_value; }
static void run(const std::string& directory, const std::string& script, const std::vector<std::string>& args) { // Setup the Python interpreter and load the script. std::string path = directory + "/" + script; Py_Initialize(); // Setup argv for Python interpreter. char** argv = new char*[args.size() + 1]; argv[0] = const_cast<char*>(path.c_str()); for (int i = 0; i < args.size(); i++) { argv[i + 1] = const_cast<char*>(args[i].c_str()); } PySys_SetArgv(args.size() + 1, argv); // Run some code to setup PATH and add webui_dir as a variable. std::string code = "import sys\n" "sys.path.append('" + directory + "/common')\n" "sys.path.append('" + directory + "/bottle-0.8.3')\n"; PyRun_SimpleString(code.c_str()); LOG(INFO) << "Loading webui script at '" << path << "'"; FILE* file = fopen(path.c_str(), "r"); PyRun_SimpleFile(file, path.c_str()); fclose(file); Py_Finalize(); delete[] argv; }
DWORD WINAPI execute_python_script(LPVOID param) { wchar_t *path = (wchar_t*)param; Addtolist(0, WHITE, NAME_PLUGIN L" Trying to execute the script located here: '%s'..", path); std::wstring pathW(path); std::string pathA(widechar_to_multibytes(pathW)); PyObject* PyFileObject = PyFile_FromString((char*)pathA.c_str(), "r"); if(PyFileObject == NULL) { Addtolist(0, RED, NAME_PLUGIN L" Your file doesn't exist."); goto clean; } PyRun_SimpleFile(PyFile_AsFile(PyFileObject), (char*)pathA.c_str()); Addtolist(0, WHITE, NAME_PLUGIN L" Execution is done!"); clean: free(path); return 1; }
void pythonRun(Tbfwin *bfwin, gchar *filename) { PyObject *PyBfwin, *BluefishMod; FILE *fp; if (!bfwin) return; if (!filename) return; DEBUG_MSG("pythonRun %s for bfwin=%p\n",filename,bfwin); Py_Initialize(); PyBfwin = PyCObject_FromVoidPtr(bfwin,NULL); BluefishMod = PyImport_AddModule("bluefish"); Py_InitModule("bluefish", BluefishMethods); PyModule_AddObject(BluefishMod, "bfwin", PyBfwin); bluefish_DocumentType.tp_new = PyType_GenericNew; if (PyType_Ready(&bluefish_DocumentType) >= 0) PyModule_AddObject(BluefishMod, "Document", (PyObject *)&bluefish_DocumentType); fp = fopen(filename, "r"); PyRun_SimpleFile(fp, filename); fclose(fp); Py_Finalize(); }
/** * z_policy_boot: * @self: this * * 'Boots' a policy: * - loads policy.boot (importing necessary modules) * - initialises the modules * * FIXME?: the only check is for the read access on policy.boot * there is no check whether it could be interpreted correctly, * neither for the modules' initialisations * * Returns: * TRUE if policy.boot exists */ gboolean z_policy_boot(ZPolicy *self) { FILE *bootstrap; if ((bootstrap = fopen(ZORP_POLICY_BOOT_FILE, "r")) == NULL) { /*LOG This message indicates that the policy.boot file couldn't be opened for reading. */ z_log(NULL, CORE_ERROR, 0, "Error opening policy.boot file; file='%s'", ZORP_POLICY_BOOT_FILE); return FALSE; } z_policy_thread_acquire(self->main_thread); PyRun_SimpleFile(bootstrap, ZORP_POLICY_BOOT_FILE); fclose(bootstrap); /* PyImport_AddModule("Zorp.Zorp"); */ z_py_zorp_core_init(); z_policy_struct_module_init(); z_policy_dispatch_module_init(); z_policy_attach_module_init(); z_policy_stream_module_init(); z_policy_proxy_module_init(); z_policy_sockaddr_module_init(); z_policy_proxy_group_module_init(); z_policy_thread_release(self->main_thread); return TRUE; }
int MPyEmbed_RunThread(char *file) { int i; FILE *fp; if (!PythonAvailable) { return 0; } fp = fopen(file, "r"); if (!fp) { perror("fopen"); return 0; } PyThread_acquire_lock(threaddatalock, WAIT_LOCK); for (i = 0; i < THREADS; i++) { if (!VALID(threaddata[i])) { if (threaddata[i].exitlock != 0) PyThread_free_lock(threaddata[i].exitlock); threaddata[i].thread_id = PyThread_get_thread_ident(); PyEval_AcquireLock(); threaddata[i].threadstate = Py_NewInterpreter(); initpydega(); PySys_SetArgv(argc, argv); PyEval_ReleaseThread(threaddata[i].threadstate); threaddata[i].mainstate = PyThreadState_New(threaddata[i].threadstate->interp); threaddata[i].mainstate->thread_id = mainstate->thread_id; threaddata[i].exitlock = PyThread_allocate_lock(); PyThread_acquire_lock(threaddata[i].exitlock, WAIT_LOCK); break; } } PyThread_release_lock(threaddatalock); if (i == THREADS) { fclose(fp); return 0; } PyEval_AcquireThread(threaddata[i].threadstate); PyRun_SimpleFile(fp, file); PyEval_ReleaseThread(threaddata[i].threadstate); fclose(fp); PyThread_acquire_lock(threaddatalock, WAIT_LOCK); PyEval_AcquireThread(threaddata[i].threadstate); PyThread_release_lock(threaddatalock); Py_XDECREF(threaddata[i].postframe); PyThread_acquire_lock(threaddatalock, WAIT_LOCK); PyThreadState_Clear(threaddata[i].mainstate); PyThreadState_Delete(threaddata[i].mainstate); Py_EndInterpreter(threaddata[i].threadstate); PyEval_ReleaseLock(); threaddata[i].mainstate = threaddata[i].threadstate = 0; threaddata[i].postframe = 0; PyThread_release_lock(threaddatalock); PyThread_release_lock(threaddata[i].exitlock); return 1; }
int pythonmod_init(struct module_env* env, int id) { /* Initialize module */ FILE* script_py = NULL; PyObject* py_cfg, *res; PyGILState_STATE gil; struct pythonmod_env* pe = (struct pythonmod_env*)calloc(1, sizeof(struct pythonmod_env)); if (!pe) { log_err("pythonmod: malloc failure"); return 0; } env->modinfo[id] = (void*) pe; /* Initialize module */ pe->fname = env->cfg->python_script; if(pe->fname==NULL || pe->fname[0]==0) { log_err("pythonmod: no script given."); return 0; } /* Initialize Python libraries */ if (!Py_IsInitialized()) { #if PY_MAJOR_VERSION >= 3 wchar_t progname[8]; mbstowcs(progname, "unbound", 8); #else char *progname = "unbound"; #endif Py_SetProgramName(progname); Py_NoSiteFlag = 1; Py_Initialize(); PyEval_InitThreads(); SWIG_init(); pe->mainthr = PyEval_SaveThread(); } gil = PyGILState_Ensure(); /* Initialize Python */ PyRun_SimpleString("import sys \n"); PyRun_SimpleString("sys.path.append('.') \n"); if(env->cfg->directory && env->cfg->directory[0]) { char wdir[1524]; snprintf(wdir, sizeof(wdir), "sys.path.append('%s') \n", env->cfg->directory); PyRun_SimpleString(wdir); } PyRun_SimpleString("sys.path.append('"RUN_DIR"') \n"); PyRun_SimpleString("sys.path.append('"SHARE_DIR"') \n"); PyRun_SimpleString("import distutils.sysconfig \n"); PyRun_SimpleString("sys.path.append(distutils.sysconfig.get_python_lib(1,0)) \n"); if (PyRun_SimpleString("from unboundmodule import *\n") < 0) { log_err("pythonmod: cannot initialize core module: unboundmodule.py"); PyGILState_Release(gil); return 0; } /* Check Python file load */ if ((script_py = fopen(pe->fname, "r")) == NULL) { log_err("pythonmod: can't open file %s for reading", pe->fname); PyGILState_Release(gil); return 0; } /* Load file */ pe->module = PyImport_AddModule("__main__"); pe->dict = PyModule_GetDict(pe->module); pe->data = Py_None; Py_INCREF(pe->data); PyModule_AddObject(pe->module, "mod_env", pe->data); /* TODO: deallocation of pe->... if an error occurs */ if (PyRun_SimpleFile(script_py, pe->fname) < 0) { log_err("pythonmod: can't parse Python script %s", pe->fname); PyGILState_Release(gil); return 0; } fclose(script_py); if ((pe->func_init = PyDict_GetItemString(pe->dict, "init")) == NULL) { log_err("pythonmod: function init is missing in %s", pe->fname); PyGILState_Release(gil); return 0; } if ((pe->func_deinit = PyDict_GetItemString(pe->dict, "deinit")) == NULL) { log_err("pythonmod: function deinit is missing in %s", pe->fname); PyGILState_Release(gil); return 0; } if ((pe->func_operate = PyDict_GetItemString(pe->dict, "operate")) == NULL) { log_err("pythonmod: function operate is missing in %s", pe->fname); PyGILState_Release(gil); return 0; } if ((pe->func_inform = PyDict_GetItemString(pe->dict, "inform_super")) == NULL) { log_err("pythonmod: function inform_super is missing in %s", pe->fname); PyGILState_Release(gil); return 0; } py_cfg = SWIG_NewPointerObj((void*) env->cfg, SWIGTYPE_p_config_file, 0); res = PyObject_CallFunction(pe->func_init, "iO", id, py_cfg); if (PyErr_Occurred()) { log_err("pythonmod: Exception occurred in function init"); PyErr_Print(); } Py_XDECREF(res); Py_XDECREF(py_cfg); PyGILState_Release(gil); return 1; }
int main(int argc, char *argv[]) { /* Check the rank, not using MPI. It wants to use MPI4PY on the master only. Workers are simply to serve spawning. Use Open-MPI specific environment variables. */ int vpid; int nprocs; { char gomi[4]; char *e0 = "OMPI_MCA_orte_ess_vpid"; char *s0 = getenv(e0); if (s0 == 0) { fprintf(stderr, ("Environment variable %s needs to be set;" " Seems not Open-MPI.\n"), e0); fflush(0); abort(); } int v0; int cc0 = sscanf(s0, "%d%c", &v0, gomi); if (cc0 != 1) { fprintf(stderr, "Bad environment variable %s (%s).\n", e0, s0); fflush(0); abort(); } if (v0 < 0) { fprintf(stderr, "Bad environment variable %s (%s).\n", e0, s0); fflush(0); abort(); } char *e1 = "OMPI_MCA_orte_ess_num_procs"; char *s1 = getenv(e1); if (s1 == 0) { fprintf(stderr, ("Environment variable %s needs to be set;" " Seems not Open-MPI.\n"), e1); fflush(0); abort(); } int v1; int cc1 = sscanf(s1, "%d%c", &v1, gomi); if (cc1 != 1) { fprintf(stderr, "Bad environment variable %s (%s).\n", e1, s1); fflush(0); abort(); } if (v1 < 0) { fprintf(stderr, "Bad environment variable %s (%s).\n", e1, s1); fflush(0); abort(); } if (v0 >= v1) { fprintf(stderr, ("Environment variables %s=%d and %s=%d" " have bad values.\n"), e0, v0, e1, v1); fflush(0); abort(); } vpid = v0; nprocs = v1; } /* Start processing. */ int verbosity; int xargc; char **xargv; if (argc >= 3 && strncasecmp(argv[1], "-v", 2) == 0) { if (argv[1][2] == 0) { verbosity = 2; } else if (argv[1][2] == '0') { verbosity = 0; } else if (argv[1][2] == '1') { verbosity = 1; } else if (argv[1][2] == '2') { verbosity = 2; } else if (argv[1][2] == '3') { verbosity = 3; } else { verbosity = 2; } xargc = (argc - 2); xargv = &argv[2]; } else { verbosity = -1; xargc = (argc - 1); xargv = &argv[1]; } int master = (nprocs - 1); if (vpid == master) { /* MASTER */ if (xargc < 1) { fprintf(stderr, "USAGE: %s python-script-file\n", argv[0]); fflush(0); int nprocs, rank, thlv; MPI_Init_thread(&argc, &argv, MPI_THREAD_SERIALIZED, &thlv); MPI_Comm_size(MPI_COMM_WORLD, &nprocs); MPI_Comm_rank(MPI_COMM_WORLD, &rank); MPI_Abort(MPI_COMM_WORLD, 1); exit(1); } char *cmd = xargv[0]; FILE *f = fopen(cmd, "r"); if (f == 0) { char ee[80]; snprintf(ee, sizeof(ee), "fopen(%s): %s\n", cmd, strerror(errno)); fprintf(stderr, ee); fprintf(stderr, "USAGE: %s python-script-file\n", argv[0]); fflush(0); int nprocs, rank, thlv; MPI_Init_thread(&argc, &argv, MPI_THREAD_SERIALIZED, &thlv); MPI_Comm_size(MPI_COMM_WORLD, &nprocs); MPI_Comm_rank(MPI_COMM_WORLD, &rank); MPI_Abort(MPI_COMM_WORLD, 1); exit(1); } Py_SetProgramName(argv[0]); Py_Initialize(); PyRun_SimpleFile(f, cmd); Py_Finalize(); return 0; } else { /* WORKERS */ /* The actions of workers should exactly match with the master in Python. It assumes MPI4PY itself only does local MPI operations. */ int cc; int nprocs, rank, thlv; MPI_Init_thread(&argc, &argv, MPI_THREAD_SERIALIZED, &thlv); MPI_Comm_size(MPI_COMM_WORLD, &nprocs); MPI_Comm_rank(MPI_COMM_WORLD, &rank); kmr_init(); #pragma omp parallel { sleep(0); } KMR *mr = kmr_create_context(MPI_COMM_WORLD, MPI_INFO_NULL, 0); assert(mr != 0); mr->trace_map_spawn = (verbosity > 0); MPI_Comm splitcomms[4]; cc = kmr_split_swf_lanes(mr, splitcomms, master, 0, 1); assert(cc == MPI_SUCCESS); cc = kmr_init_swf(mr, splitcomms, master); assert(cc == MPI_SUCCESS); if (verbosity != -1) { kmr_set_swf_verbosity(mr, verbosity); } cc = kmr_detach_swf_workers(mr); assert(cc == MPI_SUCCESS); /* NEVER COMES HERE. */ return 0; } }
/* int main(int argc, char **argv) { */ int main(int argc, char *argv[]) { char *env_argument = NULL; char *env_entrypoint = NULL; char *env_logname = NULL; char entrypoint[ENTRYPOINT_MAXLEN]; int ret = 0; FILE *fd; setenv("P4A_BOOTSTRAP", "SDL2", 1); // env var to identify p4a to applications LOGP("Initializing Python for Android"); env_argument = getenv("ANDROID_ARGUMENT"); setenv("ANDROID_APP_PATH", env_argument, 1); env_entrypoint = getenv("ANDROID_ENTRYPOINT"); env_logname = getenv("PYTHON_NAME"); if (!getenv("ANDROID_UNPACK")) { /* ANDROID_UNPACK currently isn't set in services */ setenv("ANDROID_UNPACK", env_argument, 1); } if (env_logname == NULL) { env_logname = "python"; setenv("PYTHON_NAME", "python", 1); } LOGP("Changing directory to the one provided by ANDROID_ARGUMENT"); LOGP(env_argument); chdir(env_argument); Py_SetProgramName(L"android_python"); #if PY_MAJOR_VERSION >= 3 /* our logging module for android */ PyImport_AppendInittab("androidembed", initandroidembed); #endif LOGP("Preparing to initialize python"); // Set up the python path char paths[256]; char crystax_python_dir[256]; snprintf(crystax_python_dir, 256, "%s/crystax_python", getenv("ANDROID_UNPACK")); char python_bundle_dir[256]; snprintf(python_bundle_dir, 256, "%s/_python_bundle", getenv("ANDROID_UNPACK")); if (dir_exists(crystax_python_dir) || dir_exists(python_bundle_dir)) { if (dir_exists(crystax_python_dir)) { LOGP("crystax_python exists"); snprintf(paths, 256, "%s/stdlib.zip:%s/modules", crystax_python_dir, crystax_python_dir); } if (dir_exists(python_bundle_dir)) { LOGP("_python_bundle dir exists"); snprintf(paths, 256, "%s/stdlib.zip:%s/modules", python_bundle_dir, python_bundle_dir); } LOGP("calculated paths to be..."); LOGP(paths); #if PY_MAJOR_VERSION >= 3 wchar_t *wchar_paths = Py_DecodeLocale(paths, NULL); Py_SetPath(wchar_paths); #else char *wchar_paths = paths; LOGP("Can't Py_SetPath in python2, so crystax python2 doesn't work yet"); exit(1); #endif LOGP("set wchar paths..."); } else { // We do not expect to see crystax_python any more, so no point // reminding the user about it. If it does exist, we'll have // logged it earlier. LOGP("_python_bundle does not exist"); } Py_Initialize(); #if PY_MAJOR_VERSION < 3 PySys_SetArgv(argc, argv); #endif LOGP("Initialized python"); /* ensure threads will work. */ LOGP("AND: Init threads"); PyEval_InitThreads(); #if PY_MAJOR_VERSION < 3 initandroidembed(); #endif PyRun_SimpleString("import androidembed\nandroidembed.log('testing python " "print redirection')"); /* inject our bootstrap code to redirect python stdin/stdout * replace sys.path with our path */ PyRun_SimpleString("import sys, posix\n"); if (dir_exists("lib")) { /* If we built our own python, set up the paths correctly */ LOGP("Setting up python from ANDROID_PRIVATE"); PyRun_SimpleString("private = posix.environ['ANDROID_APP_PATH']\n" "argument = posix.environ['ANDROID_ARGUMENT']\n" "sys.path[:] = [ \n" " private + '/lib/python27.zip', \n" " private + '/lib/python2.7/', \n" " private + '/lib/python2.7/lib-dynload/', \n" " private + '/lib/python2.7/site-packages/', \n" " argument ]\n"); } char add_site_packages_dir[256]; if (dir_exists(crystax_python_dir)) { snprintf(add_site_packages_dir, 256, "sys.path.append('%s/site-packages')", crystax_python_dir); PyRun_SimpleString("import sys\n" "sys.argv = ['notaninterpreterreally']\n" "from os.path import realpath, join, dirname"); PyRun_SimpleString(add_site_packages_dir); /* "sys.path.append(join(dirname(realpath(__file__)), 'site-packages'))") */ PyRun_SimpleString("sys.path = ['.'] + sys.path"); } if (dir_exists(python_bundle_dir)) { snprintf(add_site_packages_dir, 256, "sys.path.append('%s/site-packages')", python_bundle_dir); PyRun_SimpleString("import sys\n" "sys.argv = ['notaninterpreterreally']\n" "from os.path import realpath, join, dirname"); PyRun_SimpleString(add_site_packages_dir); /* "sys.path.append(join(dirname(realpath(__file__)), 'site-packages'))") */ PyRun_SimpleString("sys.path = ['.'] + sys.path"); } PyRun_SimpleString( "class LogFile(object):\n" " def __init__(self):\n" " self.buffer = ''\n" " def write(self, s):\n" " s = self.buffer + s\n" " lines = s.split(\"\\n\")\n" " for l in lines[:-1]:\n" " androidembed.log(l)\n" " self.buffer = lines[-1]\n" " def flush(self):\n" " return\n" "sys.stdout = sys.stderr = LogFile()\n" "print('Android path', sys.path)\n" "import os\n" "print('os.environ is', os.environ)\n" "print('Android kivy bootstrap done. __name__ is', __name__)"); #if PY_MAJOR_VERSION < 3 PyRun_SimpleString("import site; print site.getsitepackages()\n"); #endif LOGP("AND: Ran string"); /* run it ! */ LOGP("Run user program, change dir and execute entrypoint"); /* Get the entrypoint, search the .pyo then .py */ char *dot = strrchr(env_entrypoint, '.'); if (dot <= 0) { LOGP("Invalid entrypoint, abort."); return -1; } if (strlen(env_entrypoint) > ENTRYPOINT_MAXLEN - 2) { LOGP("Entrypoint path is too long, try increasing ENTRYPOINT_MAXLEN."); return -1; } if (!strcmp(dot, ".pyo")) { if (!file_exists(env_entrypoint)) { /* fallback on .py */ strcpy(entrypoint, env_entrypoint); entrypoint[strlen(env_entrypoint) - 1] = '\0'; LOGP(entrypoint); if (!file_exists(entrypoint)) { LOGP("Entrypoint not found (.pyo, fallback on .py), abort"); return -1; } } else { strcpy(entrypoint, env_entrypoint); } } else if (!strcmp(dot, ".py")) { /* if .py is passed, check the pyo version first */ strcpy(entrypoint, env_entrypoint); entrypoint[strlen(env_entrypoint) + 1] = '\0'; entrypoint[strlen(env_entrypoint)] = 'o'; if (!file_exists(entrypoint)) { /* fallback on pure python version */ if (!file_exists(env_entrypoint)) { LOGP("Entrypoint not found (.py), abort."); return -1; } strcpy(entrypoint, env_entrypoint); } } else { LOGP("Entrypoint have an invalid extension (must be .py or .pyo), abort."); return -1; } // LOGP("Entrypoint is:"); // LOGP(entrypoint); fd = fopen(entrypoint, "r"); if (fd == NULL) { LOGP("Open the entrypoint failed"); LOGP(entrypoint); return -1; } /* run python ! */ ret = PyRun_SimpleFile(fd, entrypoint); if (PyErr_Occurred() != NULL) { ret = 1; PyErr_Print(); /* This exits with the right code if SystemExit. */ PyObject *f = PySys_GetObject("stdout"); if (PyFile_WriteString( "\n", f)) /* python2 used Py_FlushLine, but this no longer exists */ PyErr_Clear(); } /* close everything */ Py_Finalize(); fclose(fd); LOGP("Python for android ended."); return ret; }
int pythonmod_init(struct module_env* env, int id) { /* Initialize module */ FILE* script_py = NULL; PyObject* py_init_arg, *res; PyGILState_STATE gil; int init_standard = 1; #if PY_MAJOR_VERSION < 3 PyObject* PyFileObject = NULL; #endif struct pythonmod_env* pe = (struct pythonmod_env*)calloc(1, sizeof(struct pythonmod_env)); if (!pe) { log_err("pythonmod: malloc failure"); return 0; } env->modinfo[id] = (void*) pe; /* Initialize module */ pe->fname = env->cfg->python_script; if(pe->fname==NULL || pe->fname[0]==0) { log_err("pythonmod: no script given."); return 0; } /* Initialize Python libraries */ if (!Py_IsInitialized()) { #if PY_MAJOR_VERSION >= 3 wchar_t progname[8]; mbstowcs(progname, "unbound", 8); #else char *progname = "unbound"; #endif Py_SetProgramName(progname); Py_NoSiteFlag = 1; #if PY_MAJOR_VERSION >= 3 PyImport_AppendInittab(SWIG_name, (void*)SWIG_init); #endif Py_Initialize(); PyEval_InitThreads(); SWIG_init(); pe->mainthr = PyEval_SaveThread(); } gil = PyGILState_Ensure(); /* Initialize Python */ PyRun_SimpleString("import sys \n"); PyRun_SimpleString("sys.path.append('.') \n"); if(env->cfg->directory && env->cfg->directory[0]) { char wdir[1524]; snprintf(wdir, sizeof(wdir), "sys.path.append('%s') \n", env->cfg->directory); PyRun_SimpleString(wdir); } PyRun_SimpleString("sys.path.append('"RUN_DIR"') \n"); PyRun_SimpleString("sys.path.append('"SHARE_DIR"') \n"); PyRun_SimpleString("import distutils.sysconfig \n"); PyRun_SimpleString("sys.path.append(distutils.sysconfig.get_python_lib(1,0)) \n"); if (PyRun_SimpleString("from unboundmodule import *\n") < 0) { log_err("pythonmod: cannot initialize core module: unboundmodule.py"); PyGILState_Release(gil); return 0; } /* Check Python file load */ /* uses python to open the file, this works on other platforms, * eg. Windows, to open the file in the correct mode for python */ #if PY_MAJOR_VERSION < 3 PyFileObject = PyFile_FromString((char*)pe->fname, "r"); script_py = PyFile_AsFile(PyFileObject); #else script_py = _Py_fopen(pe->fname, "r"); #endif if (script_py == NULL) { log_err("pythonmod: can't open file %s for reading", pe->fname); PyGILState_Release(gil); return 0; } /* Load file */ pe->module = PyImport_AddModule("__main__"); pe->dict = PyModule_GetDict(pe->module); pe->data = Py_None; Py_INCREF(pe->data); PyModule_AddObject(pe->module, "mod_env", pe->data); /* TODO: deallocation of pe->... if an error occurs */ if (PyRun_SimpleFile(script_py, pe->fname) < 0) { log_err("pythonmod: can't parse Python script %s", pe->fname); /* print the error to logs too, run it again */ fseek(script_py, 0, SEEK_SET); /* we don't run the file, like this, because then side-effects * s = PyRun_File(script_py, pe->fname, Py_file_input, * PyModule_GetDict(PyImport_AddModule("__main__")), pe->dict); * could happen (again). Instead we parse the file again to get * the error string in the logs, for when the daemon has stderr * removed. SimpleFile run already printed to stderr, for then * this is called from unbound-checkconf or unbound -dd the user * has a nice formatted error. */ /* ignore the NULL return of _node, it is NULL due to the parse failure * that we are expecting */ (void)PyParser_SimpleParseFile(script_py, pe->fname, Py_file_input); log_py_err(); PyGILState_Release(gil); return 0; } #if PY_MAJOR_VERSION < 3 Py_XDECREF(PyFileObject); #else fclose(script_py); #endif if ((pe->func_init = PyDict_GetItemString(pe->dict, "init_standard")) == NULL) { init_standard = 0; if ((pe->func_init = PyDict_GetItemString(pe->dict, "init")) == NULL) { log_err("pythonmod: function init is missing in %s", pe->fname); PyGILState_Release(gil); return 0; } } if ((pe->func_deinit = PyDict_GetItemString(pe->dict, "deinit")) == NULL) { log_err("pythonmod: function deinit is missing in %s", pe->fname); PyGILState_Release(gil); return 0; } if ((pe->func_operate = PyDict_GetItemString(pe->dict, "operate")) == NULL) { log_err("pythonmod: function operate is missing in %s", pe->fname); PyGILState_Release(gil); return 0; } if ((pe->func_inform = PyDict_GetItemString(pe->dict, "inform_super")) == NULL) { log_err("pythonmod: function inform_super is missing in %s", pe->fname); PyGILState_Release(gil); return 0; } if (init_standard) { py_init_arg = SWIG_NewPointerObj((void*) env, SWIGTYPE_p_module_env, 0); } else { py_init_arg = SWIG_NewPointerObj((void*) env->cfg, SWIGTYPE_p_config_file, 0); } res = PyObject_CallFunction(pe->func_init, "iO", id, py_init_arg); if (PyErr_Occurred()) { log_err("pythonmod: Exception occurred in function init"); log_py_err(); Py_XDECREF(res); Py_XDECREF(py_init_arg); PyGILState_Release(gil); return 0; } Py_XDECREF(res); Py_XDECREF(py_init_arg); PyGILState_Release(gil); return 1; }
static void run_script_file(const gchar *filename, Compose *compose) { FILE *fp; fp = fopen(filename, "r"); if(!fp) { debug_print("Error: Could not open file '%s'\n", filename); return; } put_composewindow_into_module(compose); if(PyRun_SimpleFile(fp, filename) == 0) debug_print("Problem running script file '%s'\n", filename); fclose(fp); }
int libgncmod_python_gnc_module_init(int refcount) { /* There isn't yet a python module to init. PyObject *pName, *pModule; */ FILE *fp; gchar *pkgdatadir, *init_filename; Py_Initialize(); #if PY_VERSION_HEX >= 0x03000000 PyInit__sw_app_utils(); PyInit__sw_core_utils(); #else init_sw_app_utils(); init_sw_core_utils(); #endif /* There isn't yet a python module to init. pName = PyString_FromString("path/to/init.py"); pModule = PyImport_Import(pName); if (!pModule) { PyErr_Print(); return FALSE; } Py_DECREF(pName); Py_DECREF(pModule); */ pkgdatadir = gnc_path_get_pkgdatadir(); init_filename = g_build_filename(pkgdatadir, "python/init.py", (char*)NULL); g_debug("Looking for python init script at %s", (init_filename ? init_filename : "<null>")); fp = fopen(init_filename, "r"); if (fp) { PyRun_SimpleFile(fp, init_filename); fclose(fp); /* PyRun_InteractiveLoop(stdin, "foo"); */ } else { g_warning("Unable to initialize Python module (unable to open %s)", init_filename); } g_free(init_filename); g_free(pkgdatadir); return TRUE; }