int main(int argc, char *argv[]) { //\================================================================================================ //\ Initialise Python //\================================================================================================ Py_Initialize(); //\================================================================================================ //\Add our current directory to the path lookup for Python imports //\================================================================================================ PySys_SetArgv(argc, argv); //PyRun_SimpleString( "from sys import path\nfrom os import getcwd\nprint \"Current Dir\" \, getcwd()\npath.append( getcwd() + \"/scripts\" )\n" ); PyObject* sysPath = PySys_GetObject((char*)"path"); PyList_Append(sysPath, PyString_FromString("./scripts")); //\================================================================================================ //\Import the AIE C Functions into Python so that we can call them from there //\ we will need to add "import AIE" to any Python files that we wish to use these functions in //\================================================================================================ Py_InitModule("AIE", AIE_Functions); //\================================================================================================ //\ Here we are loading our Python Entry point this is the name of the game.py file that we will be //\ using for this project. //\ ** feel free to change this to anything you would like to, "game" is purely intended as a //\ suitable example. //\================================================================================================ //PyObject* pModule = ImportPythonModule("VMGameGrid"); PyObject* pModule = ImportPythonModule("game"); if (pModule != NULL) { //\============================================================================================ //\ Here we are attempting to resolve a function to call inside our python file //\ In this scenario we are looking for the main function inside our game.py file //\============================================================================================ if( AIE::InitialiseFramework( pModule ) ) { AIE::Load(pModule); do { ClearScreen(); float fDeltaTime = GetDeltaTime(); AIE::UpdatePython( pModule, fDeltaTime ); }while( !FrameworkUpdate() ); AIE::ShutdownFramework( pModule ); } Py_DECREF(pModule); } Py_Finalize(); if( g_pWindowTitle ) { delete[] g_pWindowTitle; } return 0; }
int Py_FrozenMain(int argc, char **argv) #endif { char *p; int n, sts = 1; int inspect = 0; int unbuffered = 0; #if PY_MAJOR_VERSION >= 3 && !defined(WIN_UNICODE) int i; char *oldloc; wchar_t **argv_copy = NULL; /* We need a second copies, as Python might modify the first one. */ wchar_t **argv_copy2 = NULL; if (argc > 0) { argv_copy = (wchar_t **)alloca(sizeof(wchar_t *) * argc); argv_copy2 = (wchar_t **)alloca(sizeof(wchar_t *) * argc); } #endif #if defined(MS_WINDOWS) && PY_VERSION_HEX >= 0x03040000 && PY_VERSION_HEX < 0x03060000 if (!supports_code_page(GetConsoleOutputCP()) || !supports_code_page(GetConsoleCP())) { /* Revert to the active codepage, and tell Python to use the 'mbcs' * encoding (which always uses the active codepage). In 99% of cases, * this will be the same thing anyway. */ UINT acp = GetACP(); SetConsoleCP(acp); SetConsoleOutputCP(acp); Py_SetStandardStreamEncoding("mbcs", NULL); } #endif Py_FrozenFlag = 1; /* Suppress errors from getpath.c */ Py_NoSiteFlag = 0; Py_NoUserSiteDirectory = 1; if ((p = Py_GETENV("PYTHONINSPECT")) && *p != '\0') inspect = 1; if ((p = Py_GETENV("PYTHONUNBUFFERED")) && *p != '\0') unbuffered = 1; if (unbuffered) { setbuf(stdin, (char *)NULL); setbuf(stdout, (char *)NULL); setbuf(stderr, (char *)NULL); } #if PY_MAJOR_VERSION >= 3 && !defined(WIN_UNICODE) oldloc = setlocale(LC_ALL, NULL); setlocale(LC_ALL, ""); for (i = 0; i < argc; i++) { argv_copy[i] = Py_DecodeLocale(argv[i], NULL); argv_copy2[i] = argv_copy[i]; if (!argv_copy[i]) { fprintf(stderr, "Unable to decode the command line argument #%i\n", i + 1); argc = i; goto error; } } setlocale(LC_ALL, oldloc); #endif #ifdef MS_WINDOWS PyImport_ExtendInittab(extensions); #endif /* MS_WINDOWS */ if (argc >= 1) { #if PY_MAJOR_VERSION >= 3 && !defined(WIN_UNICODE) Py_SetProgramName(argv_copy[0]); #else Py_SetProgramName(argv[0]); #endif } Py_Initialize(); #ifdef MS_WINDOWS PyWinFreeze_ExeInit(); #endif #if defined(MS_WINDOWS) && PY_VERSION_HEX < 0x03040000 if (!supports_code_page(GetConsoleOutputCP()) || !supports_code_page(GetConsoleCP())) { /* Same hack as before except for Python 2.7, which doesn't seem to have * a way to set the encoding ahead of time, and setting PYTHONIOENCODING * doesn't seem to work. Fortunately, Python 2.7 doesn't usually start * causing codec errors until the first print statement. */ PyObject *sys_stream; UINT acp = GetACP(); SetConsoleCP(acp); SetConsoleOutputCP(acp); sys_stream = PySys_GetObject("stdin"); if (sys_stream && PyFile_Check(sys_stream)) { PyFile_SetEncodingAndErrors(sys_stream, "mbcs", NULL); } sys_stream = PySys_GetObject("stdout"); if (sys_stream && PyFile_Check(sys_stream)) { PyFile_SetEncodingAndErrors(sys_stream, "mbcs", NULL); } sys_stream = PySys_GetObject("stderr"); if (sys_stream && PyFile_Check(sys_stream)) { PyFile_SetEncodingAndErrors(sys_stream, "mbcs", NULL); } } #endif if (Py_VerboseFlag) fprintf(stderr, "Python %s\n%s\n", Py_GetVersion(), Py_GetCopyright()); #if PY_MAJOR_VERSION >= 3 && !defined(WIN_UNICODE) PySys_SetArgv(argc, argv_copy); #else PySys_SetArgv(argc, argv); #endif #ifdef MACOS_APP_BUNDLE // Add the Frameworks directory to sys.path. char buffer[PATH_MAX]; uint32_t bufsize = sizeof(buffer); if (_NSGetExecutablePath(buffer, &bufsize) != 0) { assert(false); return 1; } char resolved[PATH_MAX]; if (!realpath(buffer, resolved)) { perror("realpath"); return 1; } const char *dir = dirname(resolved); sprintf(buffer, "%s/../Frameworks", dir); PyObject *sys_path = PyList_New(1); #if PY_MAJOR_VERSION >= 3 PyList_SET_ITEM(sys_path, 0, PyUnicode_FromString(buffer)); #else PyList_SET_ITEM(sys_path, 0, PyString_FromString(buffer)); #endif PySys_SetObject("path", sys_path); Py_DECREF(sys_path); // Now, store a path to the Resources directory into the main_dir pointer, // for ConfigPageManager to read out and assign to MAIN_DIR. sprintf(buffer, "%s/../Resources", dir); set_main_dir(buffer); #endif n = PyImport_ImportFrozenModule("__main__"); if (n == 0) Py_FatalError("__main__ not frozen"); if (n < 0) { PyErr_Print(); sts = 1; } else sts = 0; if (inspect && isatty((int)fileno(stdin))) sts = PyRun_AnyFile(stdin, "<stdin>") != 0; #ifdef MS_WINDOWS PyWinFreeze_ExeTerm(); #endif Py_Finalize(); #if PY_MAJOR_VERSION >= 3 && !defined(WIN_UNICODE) error: if (argv_copy2) { for (i = 0; i < argc; i++) { #if PY_MINOR_VERSION >= 4 PyMem_RawFree(argv_copy2[i]); #else PyMem_Free(argv_copy2[i]); #endif } } #endif return sts; }
int start_python() { Py_Initialize(); }
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()) { Py_SetProgramName("unbound"); 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"); 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 init_with_instance(HMODULE hmod_exe, char *frozen) { int rc = 0; HMODULE hmod_pydll; /* Py_NoSiteFlag = 1; /* Suppress 'import site' */ /* Py_InspectFlag = 1; /* Needed to determine whether to exit at SystemExit */ calc_dirname(hmod_exe); // wprintf(L"modulename %s\n", modulename); // wprintf(L"dirname %s\n", dirname); if (!locate_script(hmod_exe)) { SystemError(-1, "FATAL ERROR: Could not locate script"); // printf("FATAL ERROR locating script\n"); return -1; } hmod_pydll = load_pythondll(); if (hmod_pydll == NULL) { SystemError(-1, "FATAL ERROR: Could not load python library"); // printf("FATAL Error: could not load python library\n"); return -1; } if (PythonLoaded(hmod_pydll) < 0) { SystemError(-1, "FATAL ERROR: Failed to load some Python symbols"); // printf("FATAL Error: failed to load some Python symbols\n"); return -1; } set_vars(hmod_pydll); /* _memimporter contains the magic which allows to load dlls from memory, without unpacking them to the file-system. It is compiled into all the exe-stubs. */ PyImport_AppendInittab("_memimporter", PyInit__memimporter); /* Start the ball rolling. */ Py_SetProgramName(modulename); Py_SetPath(libfilename); Py_Initialize(); /* Set sys.frozen so apps that care can tell. If the caller did pass NULL, sys.frozen will be set to 'True'. If a string is passed this is used as the frozen attribute. run.c passes "console_exe", run_w.c passes "windows_exe", run_dll.c passes "dll" This falls apart when you consider that in some cases, a single process may end up with two py2exe generated apps - but still, we reset frozen to the correct 'current' value for the newly initializing app. */ if (frozen == NULL) PySys_SetObject("frozen", PyBool_FromLong(1)); else { PyObject *o = PyUnicode_FromString(frozen); if (o) { PySys_SetObject("frozen", o); Py_DECREF(o); } } return rc; }
// --------------------------------------------------------------------------------- PyMODINIT_FUNC initvcodec(void) { PyObject *cModule, *d; Py_Initialize(); cModule= Py_InitModule(MODULE_NAME, pyvcodec_methods); d = PyModule_GetDict( cModule ); /* register all the codecs (you can also register only the codec you wish to have smaller code */ avcodec_init(); register_avcodec(&h263_decoder); register_avcodec(&mpeg4_decoder); register_avcodec(&msmpeg4v1_decoder); register_avcodec(&msmpeg4v2_decoder); register_avcodec(&msmpeg4v3_decoder); register_avcodec(&wmv1_decoder); register_avcodec(&wmv2_decoder); register_avcodec(&h263i_decoder); register_avcodec(&mpeg2video_decoder); register_avcodec(&mpeg1video_decoder); register_avcodec(&h264_decoder); register_avcodec(&mdec_decoder); register_avcodec(&svq1_decoder); register_avcodec(&svq3_decoder); register_avcodec(&mpeg4_encoder); register_avcodec(&mpeg1video_encoder); register_avcodec(&mpeg2video_encoder); register_avcodec(&msmpeg4v3_encoder); register_avcodec(&msmpeg4v2_encoder); register_avcodec(&msmpeg4v1_encoder); decoder_type.ob_type = &PyType_Type; Py_INCREF((PyObject *)&decoder_type); if (PyModule_AddObject(cModule, DECODER_NAME, (PyObject *)&decoder_type) != 0) return; encoder_type.ob_type = &PyType_Type; Py_INCREF((PyObject *)&encoder_type); if (PyModule_AddObject(cModule, ENCODER_NAME, (PyObject *)&encoder_type) != 0) return; // Do make it visible from the module level VFrameType.ob_type = &PyType_Type; Py_INCREF((PyObject *)&VFrameType); if (PyModule_AddObject(cModule, VFRAME_NAME, (PyObject *)&VFrameType) != 0) return; PyModule_AddStringConstant( cModule, "__doc__", (char*)PYDOC ); PyModule_AddStringConstant( cModule, "version", (char*)PYMEDIA_VERSION_FULL ); PyModule_AddIntConstant( cModule, "build", PYBUILD ); PyModule_AddIntConstant( cModule, "MAX_BUFFERS", INTERNAL_BUFFER_SIZE ); g_cErr= PyErr_NewException(MODULE_NAME".VCodecError", NULL, NULL); if( g_cErr ) PyModule_AddObject( cModule, "VCodecError", g_cErr ); if (PyType_Ready(&FormatsType) < 0) return; Py_INCREF( &FormatsType ); PyModule_AddObject( cModule, "formats", Formats_New() ); }
// 调用simplehttpserver.py脚本 DWORD WINAPI ThreadFunc(PVOID pVoid) { Py_Initialize(); if (!Py_IsInitialized()) { std::cout << "Py_Initialize() failed" << std::endl; CLogMgr::GetGlobalInstance()->setLog("Py_IsInitialized() failed"); system("pause"); return 0; } if (!PyImport_AddModule("Sample")) { std::cout << "Host API module could not be created." << std::endl; } PyObject *module = Py_InitModule("Sample", Methods); if (!module) { std::cout << "Host Api functions could not be initialized." << std::endl; return 0; } int v1 = PyRun_SimpleString("import sys"); //int v2 = PyRun_SimpleString("sys.path.append('./')"); PyObject *pName = NULL; PyObject *pModule = NULL; PyObject *pDict = NULL; PyObject *pFunc1 = NULL; PyObject *pFunc2 = NULL; PyObject *pArgs1 = NULL; PyObject *pArgs2 = NULL; PyObject *pReturn1 = NULL; PyObject *pReturn2 = NULL; //载入脚本 pName = PyString_FromString("simplehttpserver"); pModule = PyImport_Import(pName); if (!pModule) { std::cout << "can not find simplehttpserver.py" << std::endl; CLogMgr::GetGlobalInstance()->setLog("can not find simplehttpserver.py"); system("pause"); return 0; } pDict = PyModule_GetDict(pModule); if (!pDict) { std::cout << "PyModule_GetDict failed" << std::endl; CLogMgr::GetGlobalInstance()->setLog("PyModule_GetDict failed"); system("pause"); return 0; } if (pReturn1 != NULL) { Py_DECREF(pReturn1); } if (pName != NULL) { Py_DECREF(pName); } if (pArgs1 != NULL) { Py_DECREF(pArgs1); } if (pArgs2 != NULL) { Py_DECREF(pArgs2); } if (pModule != NULL) { Py_DECREF(pModule); } if (pFunc1 != NULL) { Py_DECREF(pFunc1); } if (pFunc2 != NULL) { Py_DECREF(pFunc2); } if (pReturn2 != NULL) { Py_DECREF(pReturn2); } //关闭python Py_Finalize(); return 0; }
int main(int argc, char **argv) { Py_Initialize(); PyRun_SimpleString("import sys"); PyRun_SimpleString("import os"); PyRun_SimpleString("import time"); PyRun_SimpleString("import io"); PyRun_SimpleString("import socket"); //PyRun_SimpleString("print(os.getcwd())"); PyRun_SimpleString("sys.path.append(os.getcwd())"); PyRun_SimpleString("import buildtcp"); //int ret = PyRun_SimpleFile(fp, "./buildtcp.py"); PyObject *main_module = PyImport_AddModule("__main__"); PyObject *target = PyImport_AddModule("buildtcp"); if(!main_module) { printf("failed to PyImport_AddModule()\n"); return 0; } PyObject *g_dict = PyModule_GetDict(main_module); PyObject *l_dict = PyDict_New(); if(!l_dict) { printf("failed to PyDict_New()\n"); return 0; } FILE *fp = fopen("./buildtcp.py", "r"); //PyObject *res = PyRun_File(fp, "./buildtcp.py", Py_file_input, g_dict, l_dict); //PyObject *res = PyRun_File(fp, "./buildtcp.py", Py_file_input, g_dict, g_dict); //PyObject *res = PyRun_String("buildtcp.buildtcp()", Py_file_input, g_dict, l_dict); printf("PyDict_Size(g_dict):%d\n", PyDict_Size(g_dict)); print_dict(g_dict); printf("PyDict_Size(l_dict):%d\n", PyDict_Size(l_dict)); print_dict(l_dict); //PyObject *key = PyUnicode_FromString("buildtcp"); //PyObject *func = PyDict_GetItem(l_dict, key); //PyObject* f_str_exc_type = PyObject_Repr(func); //PyObject* f_pyStr = PyUnicode_AsEncodedString(f_str_exc_type, "utf-8", "Error ~"); //printf("value:%s\n", PyBytes_AsString(f_pyStr)); //res = PyObject_Call(func, PyTuple_New(), NULL); //res = PyObject_CallObject(func, NULL); PyObject *res = PyObject_CallMethodObjArgs(target, PyUnicode_FromString("buildtcp"), NULL); if(!res) { printf("failed to PyRun_File()\n"); return 0; } if(!PyObject_CheckBuffer(res)) { printf("res is not Py_buffer\n"); return 0; } Py_buffer buf; int ret = PyObject_GetBuffer(res, &buf, PyBUF_SIMPLE); if(ret == -1) { printf("failed to PyObject_GetBuffer()\n"); return 0; } hexdump("return val", buf.buf, buf.len); fclose(fp); Py_Finalize(); return 0; }
int runtime (int argc, char * argv[]) { QApplication app(argc, argv); qmlRegisterType <RFGisQMLMap> ("RFGis", 1, 0, "Map"); #if !defined (ANDROID) setenv ("AUTOCONF_PROJECT_CODE_PATH", PROJECT_CODE_PATH, 1); #else char *android_argv[3]; android_argv[0] = argv[0]; QString prefix_path = "--prefix-path=" % QString(getenv("PREFIX_PATH")); QString plugin_path = "--plugin-path=" % QString(getenv("PLUGIN_PATH")); QString app_path = QString(getenv("PREFIX_PATH")) % "/files/application"; qDebug() << "Prefix Path: " << prefix_path; qDebug() << "Plugin Path: " << plugin_path; qDebug() << "Application: " << app_path; char *alloca_prefix = new char[prefix_path.size () + 1]; char *alloca_plugin = new char[plugin_path.size () + 1]; char *alloca_app = new char[app_path.size () + 1]; memset (alloca_prefix, 0, prefix_path.size () + 1); memset (alloca_plugin, 0, plugin_path.size () + 1); memset (alloca_app, 0, app_path.size () + 1); QByteArray prefix_ba = prefix_path.toUtf8(); QByteArray plugin_ba = plugin_path.toUtf8(); QByteArray app_ba = app_path.toUtf8(); memcpy(alloca_prefix, prefix_ba.constData (), prefix_path.size ()); memcpy(alloca_plugin, plugin_ba.constData (), plugin_path.size ()); memcpy(alloca_app, app_ba.constData (), app_path.size ()); qDebug() << "Allocated Prefix" << QString(alloca_prefix); qDebug() << "Allocated Plugin" << QString(alloca_plugin); qDebug() << "Allocated Application" << QString(alloca_app); android_argv[1] = alloca_prefix; android_argv[2] = alloca_plugin; setenv ("AUTOCONF_PROJECT_CODE_PATH", alloca_app, 1); #endif Py_Initialize(); #if !defined (ANDROID) PySys_SetArgv(argc, argv); #else PySys_SetArgv(3, android_argv); #endif QString python_path = QString(getenv("PYTHONPATH")); #if defined (HAVE_GETPID) && !defined (ANDROID) && HAVE_GETPID == 1 if (python_path.size ()) { python_path += ":" + getBasePath(); } else { python_path = getBasePath(); } #endif if (python_path.size ()) python_path += ":"; python_path += "."; char *python_path_buffer = 0; char path_object_name[5]; qDebug() << "Additional python path: " << python_path; memcpy(path_object_name, "path", 5); PyObject *sys_path = PySys_GetObject(path_object_name); if (sys_path != 0) { QStringList paths_list = python_path.split(':'); for (int i = 0; i < paths_list.size(); ++i) { char *buffer = 0; QByteArray b_path = paths_list[i].toLatin1(); const char *path = b_path.data(); size_t len = strlen(path) + 1; buffer = new char[len]; memcpy(buffer, path, len); PyList_Append(sys_path, PyString_FromString(buffer)); delete buffer; } } else { QByteArray b_path = python_path.toLatin1(); const char *path = b_path.data(); size_t len = strlen(path) + 1; python_path_buffer = new char[len]; memcpy(python_path_buffer, path, len); PySys_SetPath(python_path_buffer); } PyEval_InitThreads(); preConfigure (); qDebug() << "Preconfiguration Finished"; RFGisConfigure config; RFGisInitialization (config.prefix_path (), config.plugin_path ()); configure (); #if defined (ANDROID) run_interactivenetconsole (); #endif int code = app.exec (); rfgisExit(code); return code; }
int WINAPI WinMain( HINSTANCE hInstance,HINSTANCE hPrevInstance, LPSTR lpCmdLine,int nCmdShow) { //In debug mode all logging is enabled by default. // Otherwise, additional logging must be enabled through the console. Log_Index.SetisEnabled(true); AppLog.SetisEnabled(true); ErrorLog.SetisEnabled(true); #ifdef DEBUG InputLog_Gamepads.SetisEnabled(true); InputLog_Mouse.SetisEnabled(true); InputLog_Keyboard.SetisEnabled(true); ObjectsLog.SetisEnabled(true); ScenesLog.SetisEnabled(true); ResourceLog.SetisEnabled(true); //----------------------------- AppLog.WriteMessage("Running in DEBUG mode: ALL Logging Enabled by default."); #endif AppLog.WriteMessage("The Application Entered the running state"); srand ( time(NULL)^2); //Seed rand once for the entire application. MSG msg; // Windows Message Structure bool done = false; // Bool Variable To Exit Loop ///////////////////////////////////////////////////////////////////////// //Sound Initalization MainAudio.InitOpenAL(); //3d fixed point listening MainAudio.SetListenerPos(0.0,0.0,-1.0); MainAudio.SetListenerOrien(0.0, 0.0,-1.0,0.0,1.0, 0.0); MainAudio.SetListenerVel(0.0,0.0,0.0); AppLog.WriteMessage("OpenAL Initialized Successfully"); //Initialize DirectInput & XInput Gamepads.InitDirectInput(); AppLog.WriteMessage("DirectInput Initallized Successfully"); //Initialize Python Py_Initialize(); char ** argv; argv = new char *; PySys_SetArgv(0,argv); AppLog.WriteMessage("Python Initialized Successfully"); //////////////////////////////////////////////////////////////////////// //Window Initialization //Quick #ifdef DEBUG // Create Our OpenGL Window if(!TrogWin.GetActive()) { if (!TrogWin.CreateGLWindow("Fleet",640,480,32,0)) { AppLog.WriteMessage("In Debug Mode : Windowed failed to be created."); return 0; // Quit If Window Was Not Created } TrogWin.SetActive(true); AppLog.WriteMessage("In Debug Mode : Window has been created."); AppLog.WriteMessage("OpenGL successfully initialized."); } /*!****************************************************** * The section below does not work in Debug Mode * ********************************************************/ #else // Otherwise Load Settings from Config.ini // Create Our OpenGL Window if(!TrogWin.GetActive()) { if(SM.Load_V_Settings()!=0) //Load Video Initalization settings from config.ini { //if the config file could not be found, initialize with defualt settings if (!TrogWin.CreateGLWindow("Troglodyte Version 0.7.5 ",800,600,32,false)) { return 0; // Quit If Window Was Not Created } else { AppLog.WriteMessage("Config.ini could not be loaded. Default Window Created."); } } //Convert SM.V_Settings.AppName from a string to a const char * for window display const char * WindowText=NULL; WindowText = SM.V_Settings.AppName.c_str(); if (!TrogWin.CreateGLWindow((char *)WindowText,SM.V_Settings.width,SM.V_Settings.height, SM.V_Settings.CBits,SM.V_Settings.fullscreen)) { MessageBox(NULL,"The Application could not be initialized!", "Applicaton Creation Error!",MB_ICONEXCLAMATION|MB_OK); return 0; // Quit If Window Was Not Created } TrogWin.SetActive(true); AppLog.WriteMessage("Window Succesfully created using config.ini"); } #endif //Setup our global font used throughout administrative engine functionality. float tempH = TrogWin.GetHeight() * .035; float tempW = TrogWin.GetWidth() * .075; float fontsize = tempH + tempW /2.75; fontsize=fontsize/2; CourierFont.BuildFont(fontsize,false,false,false,"Courier New"); AppLog.WriteMessage("Our Global Font was created successfully."); //Initialize our global shaders. Tex_Shade.installShaders("../resources/shaders/texture.vert", "../resources/shaders/texture.frag"); AppLog.WriteMessage("Texture shader Loaded into memory."); //Start the main Loop AppLog.WriteMessage("Entering Main Game Loop."); while(!done) { if (PeekMessage(&msg,NULL,0,0,PM_REMOVE)) //Poll for Windows Messages { if (msg.message==WM_QUIT) { done=true; } else { TranslateMessage(&msg); // Translate The Message DispatchMessage(&msg); // Dispatch The Message } } else //Otherwise update GameStates { if (TrogWin.GetActive()) { #ifdef DEBUG if (TrogWin.keys[VK_ESCAPE]) { done=true; AppLog.WriteMessage("User Pressed Escape - Requesting Application Stop."); } #endif if(TrogWin.GetActive()) // Update The Input/Audio/Visual Renderings { Gamepads.UpdateStates(); MainAudio.UpdateListenerValues(); MainState.UpdateStates(); } } } } AppLog.WriteMessage("Exiting Main Game Loop."); // Shutdown CourierFont.KillFont(); //Release global Font AppLog.WriteMessage("Global Font Released."); if(argv) //Release Python { delete argv; argv = NULL; } Gamepads.FreeDirectInput(); //Release Gamepads AppLog.WriteMessage("DirectInput Released."); MainAudio.ExitOpenAL(); //Release The SOund AppLog.WriteMessage("OpenAL Released."); #ifndef DEBUG Py_Finalize(); //Crashes in debug because not using debug .lib AppLog.WriteMessage("Python Released."); #endif TrogWin.KillGLWindow(); //Release the Window AppLog.WriteMessage("Window Was Released. Program Exited."); double result = EngineTime.CalcTimePassed(); string Apptime = FM.Seconds_2TimeString(result); AppLog.WriteMessage("Engine Ran for "+Apptime); //Close our log files. Finalize checks to see if they exist. AppLog.Finalize(); ErrorLog.Finalize(); InputLog_Gamepads.Finalize(); InputLog_Mouse.Finalize(); InputLog_Keyboard.Finalize(); ObjectsLog.Finalize(); ScenesLog.Finalize(); Log_Index.Finalize(); return(msg.wParam); // Exit The Program }
/*....................................................................*/ int main(int argc, char *argv[]){ errType err=init_local_err(); PyObject *pCurrentModel,*pLimePars,*pModule; const int maxLenName=100; char userModuleNameNoSuffix[maxLenName+1]; int modelI=-1,nPars,nImgPars,nImages,status=0; char message[STR_LEN_1]; const char *headerModuleName="limepar_classes"; inputPars par; image *img = NULL; parTemplateType *parTemplates=NULL,*imgParTemplates=NULL; if (argc < 2){ printf("Usage: casalime <name of file with pickled pars object>\n"); exit(1); } /* . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ Py_Initialize(); /* pCurrentModel should be a modellib_classes._Model instance, pLimePars should be a limepar_classes.ModelParameters instance. */ _readParsObjWrapper(argv[1], &pCurrentModel, userModuleNameNoSuffix, maxLenName, ©Temp, &pLimePars); /* Do some initialization */ setDefaultFuncStuffs(); /* in ml_funcs */ silent = 0;//********** pass it as argument? defaultFuncFlags = 0; if(pCurrentModel==Py_None){ currentModelI = MODEL_None; }else{ err = getModelI(pCurrentModel, &modelI); /* in ml_aux.c */ if(err.status!=0){ Py_DECREF(pCurrentModel); Py_DECREF(pLimePars); pyerror(err.message); } currentModelI = modelI; /* global var. */ /* Set some global arrays defined in the header of ml_models.c */ err = extractParams(pCurrentModel); /* in ml_aux.c */ if(err.status!=0){ Py_DECREF(pCurrentModel); Py_DECREF(pLimePars); pyerror(err.message); } /* Set some global arrays defined in the header of ml_funcs.c */ err = extractFuncs(pCurrentModel); /* in ml_aux.c */ if(err.status!=0){ Py_DECREF(pCurrentModel); Py_DECREF(pLimePars); pyerror(err.message); } } Py_DECREF(pCurrentModel); status = finalizeModelConfig(currentModelI); /* in ml_models.c */ if(status!=0){ Py_DECREF(pLimePars); sprintf(message, "finalizeModelConfig() returned status value %d", status); pyerror(message); } /* . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /* Construct the 'macro' list argument: */ err = setMacros(); /* in py_utils.c */ if(err.status){ Py_DECREF(pLimePars); unsetMacros(); /* in py_utils.c */ pyerror(err.message); } /* Set up any user-supplied result functions: */ if(strlen(userModuleNameNoSuffix)>0){ err = getModuleFromName(userModuleNameNoSuffix, &pModule); /* in py_utils.c */ if(err.status!=0){ /* Don't need to decref pModule. */ Py_DECREF(pLimePars); pyerror(err.message); } /* Sets up global objects defined in the header of py_utils.c */ setUpUserPythonFuncs(pModule); /* in py_utils.c */ Py_DECREF(pModule); } /* Now get the lists of attribute names from the 2 classes in limepar_classes.py: */ err = getParTemplatesWrapper(headerModuleName, &parTemplates, &nPars\ , &imgParTemplates, &nImgPars); /* in py_utils.c */ if(err.status!=0){ Py_DECREF(pLimePars); pyerror(err.message); } err = mallocInputParStrs(&par); if(err.status){ unsetMacros(); Py_DECREF(pLimePars); pyerror(err.message); } /* Finally, unpack the LIME parameter values, following the templates: */ err = readParImg(pLimePars, parTemplates, nPars, imgParTemplates\ , nImgPars, &par, &img, &nImages, pywarning); /* in py_utils.c */ if(err.status){ Py_DECREF(pLimePars); pyerror(err.message); } Py_DECREF(pLimePars); free(imgParTemplates); free(parTemplates); /* . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /* Now call the main bit of LIME: */ status = run(par, img, nImages); /* Python-object clean up before status check and possible exit. */ decrefAllUserFuncs(); /* in py_utils.c */ free(modelDblPars); /* global in header of ml_models.c */ free(modelIntPars); /* global in header of ml_models.c */ //************* why not the str pars?? freeFuncsPars(); /* in ml_funcs.c */ if(status){ sprintf(message, "Function run() returned with status %d", status); pyerror(message); } Py_Finalize(); return 0; }
int *CA_LoadCells(char *pattern, int width) { PyObject *pModuleName; // the name of the module PyObject *pModule; // the module object PyObject *pFunc; // the callable object PyObject *pWidth; // the width parameter of the CA PyObject *pArgs; // the argument list to the callable PyObject *pResult; // the result of the python invocation char *module_name = "capattern"; int i; // initialize the python interpreter Py_Initialize(); // add current directory to sys.path, so that import can succeed // alternative approach is to export: PYTHONPATH=. when starting the executable // NOTE: this is somehow wrong as it replaces sys.path //PySys_SetPath("."); // import the module pModuleName = PyString_FromString(module_name); pModule = PyImport_Import(pModuleName); if (pModule == NULL) { fprintf(stderr, "error: could not import module: %s\n", module_name); if (PyErr_Occurred()) { PyErr_Print(); } return NULL; } // get a reference to the callable with the specified name pFunc = PyObject_GetAttrString(pModule, pattern); if (pFunc == NULL) { fprintf(stderr, "error: could not find callable: %s\n", pattern); return NULL; } if (!PyCallable_Check(pFunc)) { fprintf(stderr, "error: %s is not callable\n", pattern); return NULL; } // prepare the arguments for the callable pWidth = PyInt_FromLong(width); pArgs = PyTuple_New(1); PyTuple_SetItem(pArgs, 0, pWidth); // invoke the callable with the arguments pResult = PyObject_CallObject(pFunc, pArgs); // check for errors if (PyErr_Occurred()) { PyErr_Print(); return NULL; } // check whether the result is a sequence if (!PySequence_Check(pResult)) { fprintf(stderr, "error: result is not a sequence\n"); return NULL; } // check length of returned result if (PySequence_Size(pResult) != width) { fprintf(stderr, "error: returned sequence has incorrect length\n"); } // allocate cells int *cells = (int *) malloc(width * sizeof(int)); // iterate over elements in sequence for (i=0; i<width; i++) { // check that the element is an integer PyObject *pElement; pElement = PySequence_GetItem(pResult, i); if (!PyInt_Check(pElement)) { fprintf(stderr, "error: element with index %d is not an integer\n", i); return NULL; } // check that the element is equal to one or zero int value = PyInt_AsLong(pElement); if (!((value == 0) || (value == 1))) { fprintf(stderr, "error: element with index %d is not 0 or 1\n", i); return NULL; } // get the cell *(cells+i) = value; } Py_Finalize(); return cells; }
int AppMain() { std::wstring exe_dir; // Get exe's directory { wchar_t exe_path_buf[MAX_PATH + 1]; GetModuleFileName(NULL, exe_path_buf, MAX_PATH); exe_dir = exe_path_buf; size_t last_backslash_pos = exe_dir.find_last_of(L"\\/"); if (last_backslash_pos >= 0) { exe_dir = exe_dir.substr(0, last_backslash_pos); } else { exe_dir = L""; } } // Setup environment variable "PATH" { std::wstring env_path; wchar_t tmp_buf[1]; DWORD ret = GetEnvironmentVariable(L"PATH", tmp_buf, 0); if (ret > 0) { DWORD len = ret; wchar_t * buf = (wchar_t*)malloc((len + 1) * sizeof(wchar_t)); GetEnvironmentVariable(L"PATH", buf, (len + 1) * sizeof(wchar_t)); env_path = buf; free(buf); } env_path = exe_dir + L"/lib;" + env_path; SetEnvironmentVariable(L"PATH", env_path.c_str()); } // Python home { #if defined(_DEBUG) Py_SetPythonHome(PYTHON_INSTALL_PATH); #else Py_SetPythonHome(const_cast<wchar_t*>(exe_dir.c_str())); #endif //_DEBUG } // Python module search path { std::wstring python_path; python_path += exe_dir + L"/extension;"; #if defined(_DEBUG) python_path += exe_dir + L";"; python_path += exe_dir + L"/..;"; python_path += std::wstring(PYTHON_INSTALL_PATH) + L"\\Lib;"; python_path += std::wstring(PYTHON_INSTALL_PATH) + L"\\Lib\\site-packages;"; python_path += std::wstring(PYTHON_INSTALL_PATH) + L"\\DLLs;"; #else python_path += exe_dir + L"/library.zip;"; python_path += exe_dir + L"/lib;"; #endif Py_SetPath(python_path.c_str()); } // Initialization Py_Initialize(); // Setup sys.argv { wchar_t * cmdline = GetCommandLine(); int argc; wchar_t ** argv = CommandLineToArgvW(cmdline, &argc); PySys_SetArgv(argc, argv); LocalFree(argv); } // Execute python side main script { PyObject * module = PyImport_ImportModule("cmemo_main"); if (module == NULL) { PyErr_Print(); } Py_XDECREF(module); module = NULL; } // Termination Py_Finalize(); return 0; }
int main() { // initial the interpreter char xv[100] = "abcdefg"; PyObject * tstr = PyString_FromString(xv); Py_Initialize(); if (!Py_IsInitialized()) { return -1; } // import the sys module PyRun_SimpleString("import sys"); // add the current path to sys.path PyRun_SimpleString("sys.path.append('./')"); PyObject * pModule = NULL; PyObject * pFunc = NULL; PyObject * pName = NULL; PyObject * pModule1 = NULL; PyObject * pFunc1 = NULL; PyObject * pDict = NULL; PyObject * pArgs = NULL; PyObject * pFunc2 = NULL; pName = PyString_FromString("pytest"); pModule1 = PyImport_Import(pName); if (!pModule1) { printf("can't find pytest.py"); getchar(); return -1; } pDict = PyModule_GetDict(pModule1); if (!pDict) { return -1; } pFunc1 = PyDict_GetItemString(pDict, "add"); if (!pFunc1 || !PyCallable_Check(pFunc1)) { printf("can't find function [add]"); getchar(); return -1; } pFunc2 = PyDict_GetItemString(pDict, "echo"); if (!pFunc2 || !PyCallable_Check(pFunc2)) { printf("can't find function [echo]"); getchar(); return -1; } pArgs = PyTuple_New(1); printf("array size = %d \n", PyTuple_Size(pArgs)); PyTuple_SetItem(pArgs, 0, tstr); PyObject_CallObject(pFunc2, pArgs); // create a Tuple(2) pArgs = PyTuple_New(2); // create long int and make Tumple points it PyTuple_SetItem(pArgs, 0, Py_BuildValue("l", 3)); PyTuple_SetItem(pArgs, 1, Py_BuildValue("l", 4)); // call a function with parameters PyObject_CallObject(pFunc1, pArgs); // reuse the pFunc1 parameter pFunc1 = PyDict_GetItemString(pDict, "foo"); if(!pFunc1 || !PyCallable_Check(pFunc1)) { printf("can't find function [foo]"); getchar(); return -1; } pArgs = PyTuple_New(1); PyTuple_SetItem(pArgs, 0, Py_BuildValue("l", 2)); PyObject_CallObject(pFunc1, pArgs); // a another way to import a module pModule = PyImport_ImportModule("helloworld"); // find a function in a module pFunc = PyObject_GetAttrString(pModule, "hello"); // call the function PyEval_CallObject(pFunc, NULL); // free the memory Py_DECREF(pName); Py_DECREF(pArgs); Py_DECREF(pModule1); Py_DECREF(pModule); // close python, release the resource Py_Finalize(); return 0; }
int main (int argc, char **argv) { MOD_SET_PROGRAM_NAME(argv[0]); Py_Initialize(); MOD_INIT(demangler)(); return 0; }
//------------------------------------------------------------------------------------- bool Script::install(const wchar_t* pythonHomeDir, std::wstring pyPaths, const char* moduleName, COMPONENT_TYPE componentType) { std::wstring pySysPaths = SCRIPT_PATH; wchar_t* pwpySysResPath = char2wchar(const_cast<char*>(Resmgr::getPySysResPath().c_str())); kbe_replace(pySysPaths, L"../../res/", pwpySysResPath); pyPaths += pySysPaths; free(pwpySysResPath); #if KBE_PLATFORM == PLATFORM_WIN32 Py_SetPythonHome(const_cast<wchar_t*>(pythonHomeDir)); // 先设置python的环境变量 #else std::wstring fs = L";"; std::wstring rs = L":"; size_t pos = 0; while(true) { pos = pyPaths.find(fs, pos); if (pos == std::wstring::npos) break; pyPaths.replace(pos, fs.length(), rs); } Py_SetPath(pyPaths.c_str()); char* tmpchar = wchar2char(const_cast<wchar_t*>(pyPaths.c_str())); DEBUG_MSG("Script::install: paths=%s.\n", tmpchar); free(tmpchar); #endif // Initialise python // Py_VerboseFlag = 2; Py_FrozenFlag = 1; // Warn if tab and spaces are mixed in indentation. // Py_TabcheckFlag = 1; Py_NoSiteFlag = 1; Py_IgnoreEnvironmentFlag = 1; Py_Initialize(); // python解释器的初始化 if (!Py_IsInitialized()) { ERROR_MSG("Script::install::Py_Initialize is failed!\n"); return false; } #if KBE_PLATFORM == PLATFORM_WIN32 PySys_SetPath(pyPaths.c_str()); #endif PyObject *m = PyImport_AddModule("__main__"); module_ = PyImport_AddModule(moduleName); // 添加一个脚本基础模块 if (module_ == NULL) return false; const char* componentName = COMPONENT_NAME_EX(componentType); if (PyModule_AddStringConstant(module_, "component", componentName)) { ERROR_MSG( "Script::init: Unable to set KBEngine.component to %s\n", componentName ); return false; } // 注册产生uuid方法到py APPEND_SCRIPT_MODULE_METHOD(module_, genUUID64, __py_genUUID64, METH_VARARGS, 0); #ifndef KBE_SINGLE_THREADED s_pOurInitTimeModules = PyDict_Copy( PySys_GetObject( "modules" ) ); s_pMainThreadState = PyThreadState_Get(); s_defaultContext = s_pMainThreadState; PyEval_InitThreads(); KBEConcurrency::setMainThreadIdleFunctions( &Script::releaseLock, &Script::acquireLock ); #endif ScriptStdOutErr::installScript(NULL); // 安装py重定向模块 ScriptStdOutErrHook::installScript(NULL); static struct PyModuleDef moduleDesc = { PyModuleDef_HEAD_INIT, moduleName, "This module is created by KBEngine!", -1, NULL }; PyModule_Create(&moduleDesc); // 初始化基础模块 PyObject_SetAttrString(m, moduleName, module_); // 将模块对象加入main pyStdouterr_ = new ScriptStdOutErr(); // 重定向python输出 pyStdouterrHook_ = new ScriptStdOutErrHook(); if(!pyStdouterr_->install()){ // 安装py重定向脚本模块 ERROR_MSG("Script::install::pyStdouterr_->install() is failed!\n"); SCRIPT_ERROR_CHECK(); return false; } Pickler::initialize(); Copy::initialize(); Uuid::initialize(); math::installModule("Math"); INFO_MSG("Script::install is successfully!\n"); return true; }
int c_function(int *n, float **mat) { PyObject *pModule = NULL; PyObject *pFunc = NULL; PyObject *pArg = NULL; PyObject *pRet = NULL; PyObject *pName = NULL; size_t size = *n; npy_intp *dim; int i, j; dim = (npy_intp *) malloc(sizeof(npy_intp)*(size)); for (i=0; i < size; i++) dim[i] = size; Py_Initialize(); if (!Py_IsInitialized()) { fprintf(stderr, "nao foi possivel inicializar o python!\n"); return -1; } init_numpy(); PyObject* pMat = PyArray_NewFromDescr( &PyArray_Type, PyArray_DescrFromType(NPY_FLOAT), 2, dim, NULL, (void *) *mat, NPY_ARRAY_INOUT_FARRAY, NULL); Py_INCREF(pMat); pName = PyString_FromString("function"); pModule = PyImport_Import(pName); pFunc = PyObject_GetAttrString(pModule, "py_function"); if(!PyCallable_Check(pFunc)) { printf("func not callable!\n"); return -1; } pArg = PyTuple_New (2); PyTuple_SetItem(pArg, 0, (PyObject *) PyInt_FromLong(size)); PyTuple_SetItem(pArg, 1, pMat); pRet = PyObject_CallObject(pFunc, pArg); printf("py ret: %s\n", PyString_AsString(pRet)); Py_DECREF (pMat); Py_DECREF (pName); Py_DECREF (pModule); Py_DECREF (pFunc); Py_DECREF (pArg); Py_DECREF (pRet); Py_Finalize(); return 0; }
static int Python3_Init(void) { if (!py3initialised) { #ifdef DYNAMIC_PYTHON3 if (!python3_enabled(TRUE)) { EMSG(_("E263: Sorry, this command is disabled, the Python library could not be loaded.")); goto fail; } #endif init_structs(); #ifdef PYTHON3_HOME Py_SetPythonHome(PYTHON3_HOME); #endif #if !defined(MACOS) || defined(MACOS_X_UNIX) Py_Initialize(); #else PyMac_Initialize(); #endif /* initialise threads, must be after Py_Initialize() */ PyEval_InitThreads(); #ifdef DYNAMIC_PYTHON3 get_py3_exceptions(); #endif if (PythonIO_Init()) goto fail; PyImport_AppendInittab("vim", Py3Init_vim); /* Remove the element from sys.path that was added because of our * argv[0] value in Py3Init_vim(). Previously we used an empty * string, but dependinding on the OS we then get an empty entry or * the current directory in sys.path. * Only after vim has been imported, the element does exist in * sys.path. */ PyRun_SimpleString("import vim; import sys; sys.path = list(filter(lambda x: not x.endswith('must>not&exist'), sys.path))"); // lock is created and acquired in PyEval_InitThreads() and thread // state is created in Py_Initialize() // there _PyGILState_NoteThreadState() also sets gilcounter to 1 // (python must have threads enabled!) // so the following does both: unlock GIL and save thread state in TLS // without deleting thread state PyGILState_Release(pygilstate); py3initialised = 1; } return 0; fail: /* We call PythonIO_Flush() here to print any Python errors. * This is OK, as it is possible to call this function even * if PythonIO_Init() has not completed successfully (it will * not do anything in this case). */ PythonIO_Flush(); return -1; }
int main() { s_erc error = S_SUCCESS; SList *list = NULL; SIterator *itr; SObject *a = NULL; SObject *b = NULL; SObject *c = NULL; PyObject *speectModule = NULL; /* for SWIG functions to work */ /* Initialize the Python interpreter. Required. */ Py_Initialize(); /* import speect python module */ speectModule = PyImport_ImportModule("speect"); if (speectModule == NULL) { char *py_error = s_get_python_error_str(); if (py_error) { S_CTX_ERR(&error, S_FAILURE, "main", "Call to \"PyImport_ImportModule\" failed. Reported error: %s", py_error); S_FREE(py_error); } else { S_CTX_ERR(&error, S_FAILURE, "main", "Call to \"PyImport_ImportModule\" failed"); } goto quit; } /* * initialize speect python native module */ error = s_python_native_objects_init(); if (error != S_SUCCESS) { printf("Failed to initialize Speect Python native module\n"); goto quit; } /* Create and populate Python list */ list = create_and_populate_py_list(&error); if (S_CHK_ERR(&error, S_CONTERR, "main", "Call to \"create_and_populate_py_list\" failed")) goto quit; /* * get iterator to list, should be NULL as there are no objects * in the list */ itr = S_ITERATOR_GET(list, &error); if (S_CHK_ERR(&error, S_CONTERR, "main", "Failed to get iterator to list")) goto quit; /* Create some objects and put the into the list */ a = SObjectSetInt(10, &error); if (S_CHK_ERR(&error, S_CONTERR, "main", "Failed to set int object")) goto quit; b = SObjectSetFloat(3.14, &error); if (S_CHK_ERR(&error, S_CONTERR, "main", "Failed to set float object")) goto quit; c = SObjectSetString("python list test", &error); if (S_CHK_ERR(&error, S_CONTERR, "main", "Failed to set string object")) goto quit; SListPush(list, a, &error); if (S_CHK_ERR(&error, S_CONTERR, "main", "Failed to add object to list")) goto quit; else a = NULL; /* object belongs to list now, we don't want to * delete it directly. */ SListPush(list, b, &error); if (S_CHK_ERR(&error, S_CONTERR, "main", "Failed to add object to list")) goto quit; else b = NULL; /* object belongs to list now, we don't want to * delete it directly. */ SListPush(list, c, &error); if (S_CHK_ERR(&error, S_CONTERR, "main", "Failed to add object to list")) goto quit; else c = NULL; /* object belongs to list now, we don't want to * delete it directly. */ /* * get iterator to list, should not be NULL as there are now * objects in the list */ itr = S_ITERATOR_GET(list, &error); if (S_CHK_ERR(&error, S_CONTERR, "main", "Failed to get iterator to list")) goto quit; /* iterate through list objects and print them to stdout */ for (/* NOP */; itr != NULL; itr = SIteratorNext(itr)) { char *buf; const SObject *tmp; tmp = SIteratorObject(itr, &error); if (S_CHK_ERR(&error, S_CONTERR, "main", "Failed to get list iterator object")) goto quit; buf = SObjectPrint(tmp, &error); if (S_CHK_ERR(&error, S_CONTERR, "main", "Failed to print object")) goto quit; printf("list object = %s\n", buf); S_FREE(buf); } quit: if (list != NULL) S_DELETE(list, "main", &error); if (itr != NULL) S_DELETE(itr, "main", &error); if (a != NULL) S_DELETE(a, "main", &error); if (b != NULL) S_DELETE(b, "main", &error); if (c != NULL) S_DELETE(c, "main", &error); Py_XDECREF(speectModule); Py_Finalize(); 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; /* AND: Several filepaths are hardcoded here, these must be made configurable */ /* AND: P4A uses env vars...not sure what's best */ LOGP("Initialize Python for Android"); env_argument = getenv("ANDROID_ARGUMENT"); setenv("ANDROID_APP_PATH", env_argument, 1); env_entrypoint = getenv("ANDROID_ENTRYPOINT"); env_logname = getenv("PYTHON_NAME"); if (env_logname == NULL) { env_logname = "python"; setenv("PYTHON_NAME", "python", 1); } LOGP("Changing directory to the one provided by ANDROID_ARGUMENT"); LOGP(env_argument); chdir(env_argument); Py_SetProgramName(L"android_python"); #if PY_MAJOR_VERSION >= 3 /* our logging module for android */ PyImport_AppendInittab("androidembed", initandroidembed); #endif LOGP("Preparing to initialize python"); if (dir_exists("crystax_python/")) { LOGP("crystax_python exists"); char paths[256]; snprintf(paths, 256, "%s/crystax_python/stdlib.zip:%s/crystax_python/modules", env_argument, env_argument); /* snprintf(paths, 256, "%s/stdlib.zip:%s/modules", env_argument, * env_argument); */ LOGP("calculated paths to be..."); LOGP(paths); #if PY_MAJOR_VERSION >= 3 wchar_t *wchar_paths = Py_DecodeLocale(paths, NULL); Py_SetPath(wchar_paths); #else char *wchar_paths = paths; LOGP("Can't Py_SetPath in python2, so crystax python2 doesn't work yet"); exit(1); #endif LOGP("set wchar paths..."); } else { LOGP("crystax_python does not exist"); } Py_Initialize(); #if PY_MAJOR_VERSION < 3 PySys_SetArgv(argc, argv); #endif LOGP("Initialized python"); /* ensure threads will work. */ LOGP("AND: Init threads"); PyEval_InitThreads(); #if PY_MAJOR_VERSION < 3 initandroidembed(); #endif PyRun_SimpleString("import androidembed\nandroidembed.log('testing python " "print redirection')"); /* inject our bootstrap code to redirect python stdin/stdout * replace sys.path with our path */ PyRun_SimpleString("import sys, posix\n"); if (dir_exists("lib")) { /* If we built our own python, set up the paths correctly */ LOGP("Setting up python from ANDROID_PRIVATE"); PyRun_SimpleString("private = posix.environ['ANDROID_PRIVATE']\n" "argument = posix.environ['ANDROID_ARGUMENT']\n" "sys.path[:] = [ \n" " private + '/lib/python27.zip', \n" " private + '/lib/python2.7/', \n" " private + '/lib/python2.7/lib-dynload/', \n" " private + '/lib/python2.7/site-packages/', \n" " argument ]\n"); } if (dir_exists("crystax_python")) { char add_site_packages_dir[256]; snprintf(add_site_packages_dir, 256, "sys.path.append('%s/crystax_python/site-packages')", env_argument); PyRun_SimpleString("import sys\n" "sys.argv = ['notaninterpreterreally']\n" "from os.path import realpath, join, dirname"); PyRun_SimpleString(add_site_packages_dir); /* "sys.path.append(join(dirname(realpath(__file__)), 'site-packages'))") */ PyRun_SimpleString("sys.path = ['.'] + sys.path"); } PyRun_SimpleString( "class LogFile(object):\n" " def __init__(self):\n" " self.buffer = ''\n" " def write(self, s):\n" " s = self.buffer + s\n" " lines = s.split(\"\\n\")\n" " for l in lines[:-1]:\n" " androidembed.log(l)\n" " self.buffer = lines[-1]\n" " def flush(self):\n" " return\n" "sys.stdout = sys.stderr = LogFile()\n" "print('Android path', sys.path)\n" "import os\n" "print('os.environ is', os.environ)\n" "print('Android kivy bootstrap done. __name__ is', __name__)"); #if PY_MAJOR_VERSION < 3 PyRun_SimpleString("import site; print site.getsitepackages()\n"); #endif LOGP("AND: Ran string"); /* run it ! */ LOGP("Run user program, change dir and execute entrypoint"); /* Get the entrypoint, search the .pyo then .py */ char *dot = strrchr(env_entrypoint, '.'); if (dot <= 0) { LOGP("Invalid entrypoint, abort."); return -1; } if (strlen(env_entrypoint) > ENTRYPOINT_MAXLEN - 2) { LOGP("Entrypoint path is too long, try increasing ENTRYPOINT_MAXLEN."); return -1; } if (!strcmp(dot, ".pyo")) { if (!file_exists(env_entrypoint)) { /* fallback on .py */ strcpy(entrypoint, env_entrypoint); entrypoint[strlen(env_entrypoint) - 1] = '\0'; LOGP(entrypoint); if (!file_exists(entrypoint)) { LOGP("Entrypoint not found (.pyo, fallback on .py), abort"); return -1; } } else { strcpy(entrypoint, env_entrypoint); } } else if (!strcmp(dot, ".py")) { /* if .py is passed, check the pyo version first */ strcpy(entrypoint, env_entrypoint); entrypoint[strlen(env_entrypoint) + 1] = '\0'; entrypoint[strlen(env_entrypoint)] = 'o'; if (!file_exists(entrypoint)) { /* fallback on pure python version */ if (!file_exists(env_entrypoint)) { LOGP("Entrypoint not found (.py), abort."); return -1; } strcpy(entrypoint, env_entrypoint); } } else { LOGP("Entrypoint have an invalid extension (must be .py or .pyo), abort."); return -1; } // LOGP("Entrypoint is:"); // LOGP(entrypoint); fd = fopen(entrypoint, "r"); if (fd == NULL) { LOGP("Open the entrypoint failed"); LOGP(entrypoint); return -1; } /* run python ! */ ret = PyRun_SimpleFile(fd, entrypoint); if (PyErr_Occurred() != NULL) { ret = 1; PyErr_Print(); /* This exits with the right code if SystemExit. */ PyObject *f = PySys_GetObject("stdout"); if (PyFile_WriteString( "\n", f)) /* python2 used Py_FlushLine, but this no longer exists */ PyErr_Clear(); } /* close everything */ Py_Finalize(); fclose(fd); LOGP("Python for android ended."); return ret; }
void py_start(void) { Py_Initialize(); }
void Python3Server::login() { Py_Initialize(); m_pModule = PyImport_AddModule("__main__"); }
int add_functions_from_pythonmodule(libcrange* lr, apr_pool_t* pool, set* pythonfunctions, const char* module, const char* prefix) { const char** exported_functions; const char** p; const char* module_copy = apr_pstrdup(pool, module); const char *python_inc_path = 0; static int python_interp = 0; PyObject *pModuleName; PyObject *pModule; // bootstrap the python interpreter if it hasn't been done yet if (!python_interp) { Py_Initialize(); // Set up some basic stuff to run the plugins PyRun_SimpleString(PYTHON_BOOT); python_inc_path = libcrange_getcfg(lr, "python_inc_path"); if (python_inc_path) { // FIXME this doesn't work properly // PyImport_ImportModule(module) returns NULL unless a .pyc has been generated // after the .pyc is generated things are OK, but only if PYTHONPATH is also set PyObject * pMain = PyImport_AddModule("__main__"); PyObject * pPyIncPath; PyObject * pLibcrangeLoadFile; pLibcrangeLoadFile = PyObject_GetAttrString(pMain, "libcrange_load_file"); pPyIncPath = PyString_FromString(python_inc_path); PyObject_CallFunctionObjArgs(pLibcrangeLoadFile, pMain, pPyIncPath, NULL); // return None Py_DECREF(pLibcrangeLoadFile); Py_DECREF(pPyIncPath); } } // import this particular module pModule = PyImport_ImportModule(module); if (pModule == NULL) { printf("ERR: pModule == NULL, module: %s, prefix: %s\n", module, prefix); return 0; } { // insert pModule into globals()[module] PyObject * pMain = PyImport_AddModule("__main__"); PyObject_SetAttrString(pMain, module, pModule); // pMain borrowed reference, no decref } /* get the list of functions exported by this module */ p = exported_functions = get_and_load_exported_functions(lr, pool, module, prefix); while (*p) { /* add functions to the set seen by libcrange */ set_add(pythonfunctions, *p, (void*)module_copy); ++p; } return 0; }
//--------------------------------------------------------------------------------- // Initializes python. //--------------------------------------------------------------------------------- bool CPythonManager::Initialize( void ) { // Construct a path to the python engine directory. char szPythonHome[MAX_PATH_LENGTH]; V_snprintf(szPythonHome, MAX_PATH_LENGTH, "%s/Python3", GetSourcePythonDir()); V_FixSlashes(szPythonHome); DevMsg(1, MSG_PREFIX "Python home path set to %s\n", szPythonHome); // Convert to wide char for python. wchar_t wszPythonHome[MAX_PATH_LENGTH]; V_strtowcs(szPythonHome, -1, wszPythonHome, MAX_PATH_LENGTH); // Set that as the python home directory. Py_SetPythonHome(wszPythonHome); Py_SetProgramName(wszPythonHome); Py_SetPath(wszPythonHome); // Initialize python and its namespaces. Py_Initialize(); // Print some information DevMsg(1, MSG_PREFIX "Python version %s initialized!\n", Py_GetVersion()); // Set sys.argv and update sys.path DevMsg(1, MSG_PREFIX "Setting sys.argv...\n"); ICommandLine* pCommandLine = CommandLine(); int iParamCount = pCommandLine->ParmCount(); wchar_t** argv = new wchar_t*[iParamCount]; for (int i=0; i < iParamCount; i++) { const char* szParam = pCommandLine->GetParm(i); int iParamLength = strlen(szParam); wchar_t* wszParam = new wchar_t[iParamLength+1]; // Not sure what's wrong with V_strtowcs, but it seems like it // doesn't convert the string correctly on Linux mbstowcs(wszParam, szParam, iParamLength+1); argv[i] = wszParam; } PySys_SetArgv(iParamCount, argv); // Make sure sys is imported. PyRun_SimpleString("import sys"); // Add the Python API path. AddToSysPath("/packages/source-python"); // Add operating system specific paths. #if defined(WIN32) AddToSysPath("/Python3/plat-win"); #else AddToSysPath("/Python3/plat-linux"); // We've got a bunch of linux shared objects here we need to load. AddToSysPath("/Python3/lib-dynload"); #endif // Site packages for any extra packages... AddToSysPath("/packages/site-packages"); // Add the custom packages path. AddToSysPath("/packages/custom"); // And of course, the plugins directory for script imports. AddToSysPath("/plugins"); // Initialize all converters InitConverters(); // Initialize all submodules if (!modulsp_init()) { Msg(MSG_PREFIX "Failed to initialize internal modules.\n"); return false; } // Import the main module file. DevMsg(1, MSG_PREFIX "Loading main module...\n"); try { python::import("__init__").attr("load")(); } catch( ... ) { PyErr_Print(); PyErr_Clear(); Msg(MSG_PREFIX "Failed to load the main module.\n"); return false; } return true; }
//------------------------------------------------------------------------------------- bool Script::install(const wchar_t* pythonHomeDir, std::wstring pyPaths, const char* moduleName, COMPONENT_TYPE componentType) { std::wstring pySysPaths = SCRIPT_PATH; wchar_t* pwpySysResPath = strutil::char2wchar(const_cast<char*>(Resmgr::getSingleton().getPySysResPath().c_str())); strutil::kbe_replace(pySysPaths, L"../../res/", pwpySysResPath); pyPaths += pySysPaths; free(pwpySysResPath); // 先设置python的环境变量 Py_SetPythonHome(const_cast<wchar_t*>(pythonHomeDir)); #if KBE_PLATFORM != PLATFORM_WIN32 std::wstring fs = L";"; std::wstring rs = L":"; size_t pos = 0; while(true) { pos = pyPaths.find(fs, pos); if (pos == std::wstring::npos) break; pyPaths.replace(pos, fs.length(), rs); } char* tmpchar = strutil::wchar2char(const_cast<wchar_t*>(pyPaths.c_str())); DEBUG_MSG(fmt::format("Script::install(): paths={}.\n", tmpchar)); free(tmpchar); #endif // Initialise python // Py_VerboseFlag = 2; Py_FrozenFlag = 1; // Warn if tab and spaces are mixed in indentation. // Py_TabcheckFlag = 1; Py_NoSiteFlag = 1; Py_IgnoreEnvironmentFlag = 1; Py_SetPath(pyPaths.c_str()); // python解释器的初始化 Py_Initialize(); if (!Py_IsInitialized()) { ERROR_MSG("Script::install(): Py_Initialize is failed!\n"); return false; } PyObject *m = PyImport_AddModule("__main__"); // 添加一个脚本基础模块 module_ = PyImport_AddModule(moduleName); if (module_ == NULL) return false; const char* componentName = COMPONENT_NAME_EX(componentType); if (PyModule_AddStringConstant(module_, "component", componentName)) { ERROR_MSG(fmt::format("Script::install(): Unable to set KBEngine.component to {}\n", componentName)); return false; } // 注册产生uuid方法到py APPEND_SCRIPT_MODULE_METHOD(module_, genUUID64, __py_genUUID64, METH_VARARGS, 0); if(!install_py_dlls()) { ERROR_MSG("Script::install(): install_py_dlls() is failed!\n"); return false; } // 安装py重定向模块 ScriptStdOut::installScript(NULL); ScriptStdErr::installScript(NULL); /* static struct PyModuleDef moduleDesc = { PyModuleDef_HEAD_INIT, moduleName, "This module is created by KBEngine!", -1, NULL }; // 初始化基础模块 PyModule_Create(&moduleDesc); */ // 将模块对象加入main PyObject_SetAttrString(m, moduleName, module_); PyObject_SetAttrString(module_, "__doc__", PyUnicode_FromString("This module is created by KBEngine!")); // 重定向python输出 pyStdouterr_ = new ScriptStdOutErr(); // 安装py重定向脚本模块 if(!pyStdouterr_->install()){ ERROR_MSG("Script::install::pyStdouterr_->install() is failed!\n"); delete pyStdouterr_; SCRIPT_ERROR_CHECK(); return false; } PyGC::initialize(); Pickler::initialize(); PyProfile::initialize(this); PyStruct::initialize(); Copy::initialize(); SCRIPT_ERROR_CHECK(); math::installModule("Math"); INFO_MSG(fmt::format("Script::install(): is successfully, Python=({})!\n", Py_GetVersion())); return installExtraModule("KBExtra"); }
int main(int argc, char *argv[]) { PyObject *pName, *pModule, *pDict, *pFunc; PyObject *pArgs, *pValue; int i; if (argc < 3) { fprintf(stderr,"Usage: call pythonfile funcname [args]\n"); return 1; } Py_Initialize(); pName = PyString_FromString(argv[1]); /* Error checking of pName left out */ pModule = PyImport_Import(pName); Py_DECREF(pName); if (pModule != NULL) { pFunc = PyDict_GetAttrString(pModule, argv[2]); /* pFunc is a new reference */ if (pFunc && PyCallable_Check(pFunc)) { pArgs = PyTuple_New(argc - 3); for (i = 0; i < argc - 3; ++i) { pValue = PyInt_FromLong(atoi(argv[i + 3])); if (!pValue) { Py_DECREF(pArgs); Py_DECREF(pModule); fprintf(stderr, "Cannot convert argument\n"); return 1; } /* pValue reference stolen here: */ PyTuple_SetItem(pArgs, i, pValue); } pValue = PyObject_CallObject(pFunc, pArgs); Py_DECREF(pArgs); if (pValue != NULL) { printf("Result of call: %ld\n", PyInt_AsLong(pValue)); Py_DECREF(pValue); } else { Py_DECREF(pFunc); Py_DECREF(pModule); PyErr_Print(); fprintf(stderr,"Call failed\n"); return 1; } } else { if (PyErr_Occurred()) PyErr_Print(); fprintf(stderr, "Cannot find function \"%s\"\n", argv[2]); } Py_XDECREF(pFunc); Py_DECREF(pModule); } else { PyErr_Print(); fprintf(stderr, "Failed to load \"%s\"\n", argv[1]); return 1; } Py_Finalize(); return 0; }
int main( int argc, char * * argv, char * * arg_environ ) { int n; char * s; struct bjam_option optv[ N_OPTS ]; char const * all = "all"; int status; int arg_c = argc; char * * arg_v = argv; char const * progname = argv[ 0 ]; module_t * environ_module; saved_argv0 = argv[ 0 ]; BJAM_MEM_INIT(); #ifdef OS_MAC InitGraf( &qd.thePort ); #endif --argc; ++argv; #ifdef HAVE_PYTHON #define OPTSTRING "-:l:m:d:j:p:f:gs:t:ano:qvz" #else #define OPTSTRING "-:l:m:d:j:p:f:gs:t:ano:qv" #endif if ( getoptions( argc, argv, OPTSTRING, optv ) < 0 ) { err_printf( "\nusage: %s [ options ] targets...\n\n", progname ); err_printf( "-a Build all targets, even if they are current.\n" ); err_printf( "-dx Set the debug level to x (0-9).\n" ); err_printf( "-fx Read x instead of Jambase.\n" ); /* err_printf( "-g Build from newest sources first.\n" ); */ err_printf( "-jx Run up to x shell commands concurrently.\n" ); err_printf( "-lx Limit actions to x number of seconds after which they are stopped.\n" ); err_printf( "-mx Maximum target output saved (kb), default is to save all output.\n" ); err_printf( "-n Don't actually execute the updating actions.\n" ); err_printf( "-ox Mirror all output to file x.\n" ); err_printf( "-px x=0, pipes action stdout and stderr merged into action output.\n" ); err_printf( "-q Quit quickly as soon as a target fails.\n" ); err_printf( "-sx=y Set variable x=y, overriding environment.\n" ); err_printf( "-tx Rebuild x, even if it is up-to-date.\n" ); err_printf( "-v Print the version of jam and exit.\n" ); #ifdef HAVE_PYTHON err_printf( "-z Disable Python Optimization and enable asserts\n" ); #endif err_printf( "--x Option is ignored.\n\n" ); exit( EXITBAD ); } /* Version info. */ if ( ( s = getoptval( optv, 'v', 0 ) ) ) { out_printf( "Boost.Jam Version %s. %s.\n", VERSION, OSMINOR ); out_printf( " Copyright 1993-2002 Christopher Seiwald and Perforce " "Software, Inc.\n" ); out_printf( " Copyright 2001 David Turner.\n" ); out_printf( " Copyright 2001-2004 David Abrahams.\n" ); out_printf( " Copyright 2002-2015 Rene Rivera.\n" ); out_printf( " Copyright 2003-2015 Vladimir Prus.\n" ); return EXITOK; } /* Pick up interesting options. */ if ( ( s = getoptval( optv, 'n', 0 ) ) ) { ++globs.noexec; globs.debug[ 2 ] = 1; } if ( ( s = getoptval( optv, 'p', 0 ) ) ) { /* Undocumented -p3 (acts like both -p1 -p2) means separate pipe action * stdout and stderr. */ globs.pipe_action = atoi( s ); if ( globs.pipe_action < 0 || 3 < globs.pipe_action ) { err_printf( "Invalid pipe descriptor '%d', valid values are -p[0..3]." "\n", globs.pipe_action ); exit( EXITBAD ); } } if ( ( s = getoptval( optv, 'q', 0 ) ) ) globs.quitquick = 1; if ( ( s = getoptval( optv, 'a', 0 ) ) ) anyhow++; if ( ( s = getoptval( optv, 'j', 0 ) ) ) { globs.jobs = atoi( s ); if ( globs.jobs < 1 || globs.jobs > MAXJOBS ) { err_printf( "Invalid value for the '-j' option, valid values are 1 " "through %d.\n", MAXJOBS ); exit( EXITBAD ); } } if ( ( s = getoptval( optv, 'g', 0 ) ) ) globs.newestfirst = 1; if ( ( s = getoptval( optv, 'l', 0 ) ) ) globs.timeout = atoi( s ); if ( ( s = getoptval( optv, 'm', 0 ) ) ) globs.max_buf = atoi( s ) * 1024; /* convert to kb */ #ifdef HAVE_PYTHON if ( ( s = getoptval( optv, 'z', 0 ) ) ) python_optimize = 0; /* disable python optimization */ #endif /* Turn on/off debugging */ for ( n = 0; ( s = getoptval( optv, 'd', n ) ); ++n ) { int i; /* First -d, turn off defaults. */ if ( !n ) for ( i = 0; i < DEBUG_MAX; ++i ) globs.debug[i] = 0; i = atoi( s ); if ( ( i < 0 ) || ( i >= DEBUG_MAX ) ) { out_printf( "Invalid debug level '%s'.\n", s ); continue; } /* n turns on levels 1-n. */ /* +n turns on level n. */ if ( *s == '+' ) globs.debug[ i ] = 1; else while ( i ) globs.debug[ i-- ] = 1; } /* If an output file is specified, set globs.out to that. */ if ( ( s = getoptval( optv, 'o', 0 ) ) ) { if ( !( globs.out = fopen( s, "w" ) ) ) { err_printf( "Failed to write to '%s'\n", s ); exit( EXITBAD ); } /* ++globs.noexec; */ } constants_init(); cwd_init(); { PROFILE_ENTER( MAIN ); #ifdef HAVE_PYTHON { PROFILE_ENTER( MAIN_PYTHON ); Py_OptimizeFlag = python_optimize; Py_Initialize(); { static PyMethodDef BjamMethods[] = { {"call", bjam_call, METH_VARARGS, "Call the specified bjam rule."}, {"import_rule", bjam_import_rule, METH_VARARGS, "Imports Python callable to bjam."}, {"define_action", bjam_define_action, METH_VARARGS, "Defines a command line action."}, {"variable", bjam_variable, METH_VARARGS, "Obtains a variable from bjam's global module."}, {"backtrace", bjam_backtrace, METH_VARARGS, "Returns bjam backtrace from the last call into Python."}, {"caller", bjam_caller, METH_VARARGS, "Returns the module from which the last call into Python is made."}, {NULL, NULL, 0, NULL} }; Py_InitModule( "bjam", BjamMethods ); } PROFILE_EXIT( MAIN_PYTHON ); } #endif #ifndef NDEBUG run_unit_tests(); #endif #if YYDEBUG != 0 if ( DEBUG_PARSE ) yydebug = 1; #endif /* Set JAMDATE. */ { timestamp current; timestamp_current( ¤t ); var_set( root_module(), constant_JAMDATE, list_new( outf_time( ¤t ) ), VAR_SET ); } /* Set JAM_VERSION. */ var_set( root_module(), constant_JAM_VERSION, list_push_back( list_push_back( list_new( object_new( VERSION_MAJOR_SYM ) ), object_new( VERSION_MINOR_SYM ) ), object_new( VERSION_PATCH_SYM ) ), VAR_SET ); /* Set JAMUNAME. */ #ifdef unix { struct utsname u; if ( uname( &u ) >= 0 ) { var_set( root_module(), constant_JAMUNAME, list_push_back( list_push_back( list_push_back( list_push_back( list_new( object_new( u.sysname ) ), object_new( u.nodename ) ), object_new( u.release ) ), object_new( u.version ) ), object_new( u.machine ) ), VAR_SET ); } } #endif /* unix */ /* Set JAM_TIMESTAMP_RESOLUTION. */ { timestamp fmt_resolution[ 1 ]; file_supported_fmt_resolution( fmt_resolution ); var_set( root_module(), constant_JAM_TIMESTAMP_RESOLUTION, list_new( object_new( timestamp_timestr( fmt_resolution ) ) ), VAR_SET ); } /* Load up environment variables. */ /* First into the global module, with splitting, for backward * compatibility. */ var_defines( root_module(), use_environ, 1 ); environ_module = bindmodule( constant_ENVIRON ); /* Then into .ENVIRON, without splitting. */ var_defines( environ_module, use_environ, 0 ); /* * Jam defined variables OS & OSPLAT. We load them after environment, so * that setting OS in environment does not change Jam's notion of the * current platform. */ var_defines( root_module(), othersyms, 1 ); /* Load up variables set on command line. */ for ( n = 0; ( s = getoptval( optv, 's', n ) ); ++n ) { char * symv[ 2 ]; symv[ 0 ] = s; symv[ 1 ] = 0; var_defines( root_module(), symv, 1 ); var_defines( environ_module, symv, 0 ); } /* Set the ARGV to reflect the complete list of arguments of invocation. */ for ( n = 0; n < arg_c; ++n ) var_set( root_module(), constant_ARGV, list_new( object_new( arg_v[ n ] ) ), VAR_APPEND ); /* Initialize built-in rules. */ load_builtins(); /* Add the targets in the command line to the update list. */ for ( n = 1; n < arg_c; ++n ) { if ( arg_v[ n ][ 0 ] == '-' ) { char * f = "-:l:d:j:f:gs:t:ano:qv"; for ( ; *f; ++f ) if ( *f == arg_v[ n ][ 1 ] ) break; if ( ( f[ 1 ] == ':' ) && ( arg_v[ n ][ 2 ] == '\0' ) ) ++n; } else { OBJECT * const target = object_new( arg_v[ n ] ); mark_target_for_updating( target ); object_free( target ); } } if ( list_empty( targets_to_update() ) ) mark_target_for_updating( constant_all ); /* Parse ruleset. */ { FRAME frame[ 1 ]; frame_init( frame ); for ( n = 0; ( s = getoptval( optv, 'f', n ) ); ++n ) { OBJECT * const filename = object_new( s ); parse_file( filename, frame ); object_free( filename ); } if ( !n ) parse_file( constant_plus, frame ); } status = yyanyerrors(); /* Manually touch -t targets. */ for ( n = 0; ( s = getoptval( optv, 't', n ) ); ++n ) { OBJECT * const target = object_new( s ); touch_target( target ); object_free( target ); } /* The build system may set the PARALLELISM variable to override -j * options. */ { LIST * const p = var_get( root_module(), constant_PARALLELISM ); if ( !list_empty( p ) ) { int const j = atoi( object_str( list_front( p ) ) ); if ( j < 1 || j > MAXJOBS ) out_printf( "Invalid value of PARALLELISM: %s. Valid values " "are 1 through %d.\n", object_str( list_front( p ) ), MAXJOBS ); else globs.jobs = j; } } /* KEEP_GOING overrides -q option. */ { LIST * const p = var_get( root_module(), constant_KEEP_GOING ); if ( !list_empty( p ) ) globs.quitquick = atoi( object_str( list_front( p ) ) ) ? 0 : 1; } /* Now make target. */ { PROFILE_ENTER( MAIN_MAKE ); LIST * const targets = targets_to_update(); if ( !list_empty( targets ) ) status |= make( targets, anyhow ); else status = last_update_now_status; PROFILE_EXIT( MAIN_MAKE ); } PROFILE_EXIT( MAIN ); } if ( DEBUG_PROFILE ) profile_dump(); #ifdef OPT_HEADER_CACHE_EXT hcache_done(); #endif clear_targets_to_update(); /* Widely scattered cleanup. */ property_set_done(); file_done(); rules_done(); timestamp_done(); search_done(); class_done(); modules_done(); regex_done(); cwd_done(); path_done(); function_done(); list_done(); constants_done(); object_done(); /* Close log out. */ if ( globs.out ) fclose( globs.out ); #ifdef HAVE_PYTHON Py_Finalize(); #endif BJAM_MEM_CLOSE(); return status ? EXITBAD : EXITOK; }
static int Python_Init(void) { if (!initialised) { #ifdef DYNAMIC_PYTHON if (!python_enabled(TRUE)) { EMSG(_("E263: Sorry, this command is disabled, the Python library could not be loaded.")); goto fail; } #endif #ifdef PYTHON_HOME Py_SetPythonHome(PYTHON_HOME); #endif init_structs(); #if !defined(MACOS) || defined(MACOS_X_UNIX) Py_Initialize(); #else PyMac_Initialize(); #endif /* Initialise threads, and below save the state using * PyEval_SaveThread. Without the call to PyEval_SaveThread, thread * specific state (such as the system trace hook), will be lost * between invocations of Python code. */ PyEval_InitThreads(); #ifdef DYNAMIC_PYTHON get_exceptions(); #endif if (PythonIO_Init_io()) goto fail; if (PythonMod_Init()) goto fail; globals = PyModule_GetDict(PyImport_AddModule("__main__")); /* Remove the element from sys.path that was added because of our * argv[0] value in PythonMod_Init(). Previously we used an empty * string, but depending on the OS we then get an empty entry or * the current directory in sys.path. */ PyRun_SimpleString("import sys; sys.path = filter(lambda x: x != '/must>not&exist', sys.path)"); /* lock is created and acquired in PyEval_InitThreads() and thread * state is created in Py_Initialize() * there _PyGILState_NoteThreadState() also sets gilcounter to 1 * (python must have threads enabled!) * so the following does both: unlock GIL and save thread state in TLS * without deleting thread state */ #ifndef PY_CAN_RECURSE saved_python_thread = #endif PyEval_SaveThread(); initialised = 1; } return 0; fail: /* We call PythonIO_Flush() here to print any Python errors. * This is OK, as it is possible to call this function even * if PythonIO_Init_io() has not completed successfully (it will * not do anything in this case). */ PythonIO_Flush(); return -1; }
int main(int argc, char** argv) { //初始化Python //在使用Python系统前,必须使用Py_Initialize对其 //进行初始化。它会载入Python的内建模块并添加系统路 //径到模块搜索路径中。这个函数没有返回值,检查系统 //是否初始化成功需要使用Py_IsInitialized。 Py_Initialize(); // 检查初始化是否成功 if ( !Py_IsInitialized() ) { printf("Init Error\r\n"); Sleep(10000); return -1; } // 添加当前路径 //把输入的字符串作为Python代码直接运行,返回0 //表示成功,-1表示有错。大多时候错误都是因为字符串 //中有语法错误。 PyRun_SimpleString("import sys"); PyRun_SimpleString("sys.path.append('./')"); PyObject *pName = NULL, *pModule = NULL, *pDict = NULL, *pFunc = NULL, *pArgs = NULL; // 载入名为pytest的脚本 pName = PyString_FromString("pytest"); pModule = PyImport_Import(pName); if ( !pModule ) { printf("can't find pytest.py\r\n"); Sleep(10000); return -1; } pDict = PyModule_GetDict(pModule); if ( !pDict ) { printf("can't GetDict\r\n"); Sleep(10000); return -1; } // 找出函数名为add的函数 pFunc = PyDict_GetItemString(pDict, "add"); if ( !pFunc || !PyCallable_Check(pFunc) ) { printf("can't find function [add]"); Sleep(10000); return -1; } // 参数进栈 *pArgs; pArgs = PyTuple_New(2); // PyObject* Py_BuildValue(char *format, ...) // 把C++的变量转换成一个Python对象。当需要从 // C++传递变量到Python时,就会使用这个函数。此函数 // 有点类似C的printf,但格式不同。常用的格式有 // s 表示字符串, // i 表示整型变量, // f 表示浮点数, // O 表示一个Python对象。 PyTuple_SetItem(pArgs, 0, Py_BuildValue("i",3)); PyTuple_SetItem(pArgs, 1, Py_BuildValue("i",4)); // 调用Python函数 PyObject_CallObject(pFunc, pArgs); //下面这段是查找函数foo 并执行foo pFunc = PyDict_GetItemString(pDict, "foo"); if ( !pFunc || !PyCallable_Check(pFunc) ) { printf("can't find function [foo]"); Sleep(10000); return -1; } pArgs = PyTuple_New(1); PyTuple_SetItem(pArgs, 0, Py_BuildValue("i",2)); // PyObject_CallObject(pFunc, pArgs); Py_DECREF(pName); Py_DECREF(pArgs); Py_DECREF(pModule); // 关闭Python Py_Finalize(); getchar(); return 0; }
static kbool_t python_PackupNameSpace(KonohaContext *kctx, kNameSpace *ns, int option, KTraceInfo *trace) { python_Init_count++; if(python_Init_count == 1) { Py_Initialize(); } static KDEFINE_CLASS PythonDef = { STRUCTNAME(PyObject), .cflag = 0, .init = kPyObject_Init, .free = kPyObject_Free, .p = kPyObject_p, }; KClass *cPython = KLIB kNameSpace_DefineClass(kctx, ns, NULL, &PythonDef, trace); int KType_PyObject = cPython->typeId; KDEFINE_METHOD MethodData[] = { _Public|_Const|_Im|_Coercion, _F(PyObject_toBoolean), KType_Boolean, KType_PyObject, KMethodName_To(KType_Boolean), 0, _Public|_Const|_Im|_Coercion, _F(Boolean_toPyObject), KType_PyObject, KType_Boolean, KMethodName_To(KType_PyObject), 0, _Public|_Const|_Im|_Coercion, _F(PyObject_toInt), KType_Int, KType_PyObject, KMethodName_To(KType_Int), 0, _Public|_Const|_Im|_Coercion, _F(Int_toPyObject), KType_PyObject, KType_Int, KMethodName_To(KType_PyObject), 0, _Public|_Const|_Im|_Coercion, _F(PyObject_toString), KType_String, KType_PyObject, KMethodName_To(KType_String), 0, _Public|_Const|_Im|_Coercion, _F(String_toPyObject), KType_PyObject, KType_String, KMethodName_To(KType_PyObject), 0, //_Public, _F(Array_Add), KType_void, KType_Array, KMethodName_("add"), 1, KType_0, KFieldName_("value"), // [TODO] add following konoha class. //_Public|_Const|_Im|_Coercion, _F(PyObject_toList), KType_Array, KType_PyObject, KMethodName_To(KType_Array), 0, //_Public|_Const|_Im|_Coercion, _F(Array_toPyObject), KType_PyObject, KType_Array, KMethodName_To(KType_PyObject), 0, //_Public|_Const|_Im|_Coercion, _F(PyObject_toComplex), KType_Complex, KType_PyObject, KMethodName_To(KType_Complex), 0, //_Public|_Const|_Im|_Coercion, _F(Complex_toPyObject), KType_PyObject, KType_Complex, KMethodName_To(KType_PyObject), 0, //_Public|_Const|_Im|_Coercion, _F(PyObject_toBuffer), KType_Buffer, KType_PyObject, KMethodName_To(KType_Buffer), 0, //_Public|_Const|_Im|_Coercion, _F(Buffer_toPyObject), KType_PyObject, KType_Buffer, KMethodName_To(KType_PyObject), 0, //_Public|_Const|_Im|_Coercion, _F(PyObject_toTuple), KType_Tuple, KType_PyObject, KMethodName_To(KType_Tuple), 0, //_Public|_Const|_Im|_Coercion, _F(Tuple_toPyObject), KType_PyObject, KType_Tuple, KMethodName_To(KType_PyObject), 0, //_Public|_Const|_Im|_Coercion, _F(PyObject_toDict), KType_Dict, KType_PyObject, KMethodName_To(KType_Dict), 0, //_Public|_Const|_Im|_Coercion, _F(Dict_toPyObject), KType_PyObject, KType_Dict, KMethodName_To(KType_PyObject), 0, //_Public|_Const|_Im|_Coercion, _F(PyObject_toClass), KType_Class, KType_PyObject, KMethodName_To(KType_Class), 0, //_Public|_Const|_Im|_Coercion, _F(Class_toPyObject), KType_PyObject, KType_Class, KMethodName_To(KType_PyObject), 0, //_Public|_Const|_Im|_Coercion, _F(PyObject_asFunction), KType_Function, KType_PyObject, KMethodName_To(KType_Function), 0, //_Public|_Const|_Im|_Coercion, _F(Function_toPyObject), KType_PyObject, KType_Function, KMethodName_To(KType_PyObject), 0, //_Public|_Const|_Im|_Coercion, _F(PyObject_asMethod), KType_Method, KType_PyObject, KMethodName_To(KType_Method), 0, //_Public|_Const|_Im|_Coercion, _F(Method_toPyObject), KType_PyObject, KType_Method, KMethodName_To(KType_PyObject), 0, //_Public|_Const|_Im|_Coercion, _F(PyObject_toFile), KType_File, KType_PyObject, KMethodName_To(KType_File), 0, //_Public|_Const|_Im|_Coercion, _F(File_toPyObject), KType_PyObject, KType_File, KMethodName_To(KType_PyObject), 0, //_Public|_Const|_Im|_Coercion, _F(PyObject_toModule), KType_Module, KType_PyObject, KMethodName_To(KType_Module), 0, //_Public|_Const|_Im|_Coercion, _F(Module_toPyObject), KType_PyObject, KType_Module, KMethodName_To(KType_PyObject), 0, //_Public|_Const|_Im|_Coercion, _F(PyObject_toSeqIter), KType_SeqIter, KType_PyObject, KMethodName_To(KType_SeqIter), 0, //_Public|_Const|_Im|_Coercion, _F(SeqIter_toPyObject), KType_PyObject, KType_SeqIter, KMethodName_To(KType_PyObject), 0, //_Public|_Const|_Im|_Coercion, _F(PyObject_toSlice), KType_Slice, KType_PyObject, KMethodName_To(KType_Slice), 0, //_Public|_Const|_Im|_Coercion, _F(Slice_toPyObject), KType_PyObject, KType_Slice, KMethodName_To(KType_PyObject), 0, //_Public|_Const|_Im|_Coercion, _F(PyObject_toWeakref), KType_Weakref, KType_PyObject, KMethodName_To(KType_Weakref), 0, //_Public|_Const|_Im|_Coercion, _F(Weakref_toPyObject), KType_PyObject, KType_Weakref, KMethodName_To(KType_PyObject), 0, //_Public|_Const|_Im|_Coercion, _F(PyObject_toCapsule), KType_Capsule, KType_PyObject, KMethodName_To(KType_Capsule), 0, //_Public|_Const|_Im|_Coercion, _F(Capsule_toPyObject), KType_PyObject, KType_Capsule, KMethodName_To(KType_PyObject), 0, //_Public|_Const|_Im|_Coercion, _F(PyObject_toCell), KType_Cell, KType_PyObject, KMethodName_To(KType_Cell), 0, //_Public|_Const|_Im|_Coercion, _F(Cell_toPyObject), KType_PyObject, KType_Cell, KMethodName_To(KType_PyObject), 0, //_Public|_Const|_Im|_Coercion, _F(PyObject_toGen), KType_Gen, KType_PyObject, KMethodName_To(KType_Gen), 0, //_Public|_Const|_Im|_Coercion, _F(Gen_toPyObject), KType_PyObject, KType_Gen, KMethodName_To(KType_PyObject), 0, //_Public|_Const|_Im|_Coercion, _F(Date_toPyObject), KType_PyObject, KType_Date, KMethodName_To(KType_PyObject), 0, //_Public|_Const|_Im|_Coercion, _F(PyObject_toDate), KType_Date, KType_PyObject, KMethodName_To(KType_Date), 0, //_Public|_Const|_Im|_Coercion, _F(Set_toPyObject), KType_PyObject, KType_Set, KMethodName_To(KType_PyObject), 0, //_Public|_Const|_Im|_Coercion, _F(PyObject_toSet), KType_Set, KType_PyObject, KMethodName_To(KType_Set), 0, //_Public|_Const|_Im|_Coercion, _F(Code_toPyObject), KType_PyObject, KType_Code, KMethodName_To(KType_PyObject), 0, //_Public|_Const|_Im|_Coercion, _F(PyObject_toCode), KType_Code, KType_PyObject, KMethodName_To(KType_Code), 0, _Public|_Im, _F(Python_Eval), KType_Boolean, KType_System, KFieldName_("pyEval"), 1, KType_String, KFieldName_("script"), _Public|_Im, _F(PyObject_import), KType_PyObject, KType_PyObject, KFieldName_("import"), 1, KType_String, KFieldName_("name"), _Public|_Im, _F(PyObject_), KType_PyObject, KType_PyObject, 0, 1, KType_PyObject, 0, DEND, }; KLIB kNameSpace_LoadMethodData(kctx, ns, MethodData, trace); if(KDefinedKonohaCommonModule() == true && KClass_Float != NULL) { KDEFINE_METHOD MethodData[] = { _Public|_Const|_Im|_Coercion, _F(PyObject_toFloat), KType_float, KType_PyObject, KMethodName_To(KType_float), 0, _Public|_Const|_Im|_Coercion, _F(Float_toPyObject), KType_PyObject, KType_float, KMethodName_To(KType_PyObject), 0, DEND, }; KLIB kNameSpace_LoadMethodData(kctx, ns, MethodData, trace); } return true; }