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

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

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

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

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

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

	python_state = PYTHON_STATE_FULLY_INITIALIZED;

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

	print_python_traceback_warn();
	pyerr_clear();
	Py_XDECREF(py_bt2_py_plugin_mod);
	return;
}
Exemplo n.º 2
0
void PythonModule::initialize() throw (VoreenException) {
    VoreenModule::initialize();

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

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

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

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

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

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

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

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

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

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

		const char *py_version = Py_GetVersion();
		log::msg("initialized python %s", py_version);
	}
}
Exemplo n.º 4
0
int
Py_FrozenMain(int argc, char **argv)
{
    char *p;
    int n, sts;
    int inspect = 0;
    int unbuffered = 0;

    Py_FrozenFlag = 1; /* Suppress errors from getpath.c */

    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);
    }

#ifdef MS_WINDOWS
    PyInitFrozenExtensions();
#endif /* MS_WINDOWS */
    Py_SetProgramName(argv[0]);
    Py_Initialize();
#ifdef MS_WINDOWS
    PyWinFreeze_ExeInit();
#endif

    if (Py_VerboseFlag)
        fprintf(stderr, "Python %s\n%s\n",
            Py_GetVersion(), Py_GetCopyright());

    PySys_SetArgv(argc, argv);

    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();
    return sts;
}
Exemplo n.º 5
0
BOOL CALLBACK AboutDialog::run_dlgProc(HWND hWnd, UINT Message, WPARAM wParam, LPARAM /* lParam */)
{
	switch (Message) 
	{
		case WM_INITDIALOG :
		{
			std::string message("Python ");
			message.append(Py_GetVersion());
			message.append("\n");
			message.append(Py_GetCopyright());
			
			for (size_t pos = 0;(pos = message.find("\n", pos + 1)) != std::string::npos;)
			{
				message.replace(pos, 1, "\r\n");
				++pos;
			}

			::SetWindowTextA(GetDlgItem(hWnd, IDC_COPYRIGHT), message.c_str());
			::SetWindowText(GetDlgItem(hWnd, IDC_VERSION), _T(PYSCR_VERSION_STRING));
			return TRUE;
		}
		
		case WM_CTLCOLORDLG:
			return (LONG)m_hbrBackground;

		case WM_CTLCOLORSTATIC:
		{
			HDC hdcStatic = (HDC)wParam;
			SetBkMode(hdcStatic, TRANSPARENT);
			return (LONG)m_hbrBackground;
		}

		case WM_COMMAND : 
			switch (wParam)
			{
				case IDOK :
				case IDCANCEL :
					display(false);
					return TRUE;

				default :
					break;
			}
			return FALSE;
		
		default:
			return FALSE;
	}


}
Exemplo n.º 6
0
static int __Pyx_check_binary_version(void) {
    char ctversion[4], rtversion[4];
    PyOS_snprintf(ctversion, 4, "%d.%d", PY_MAJOR_VERSION, PY_MINOR_VERSION);
    PyOS_snprintf(rtversion, 4, "%s", Py_GetVersion());
    if (ctversion[0] != rtversion[0] || ctversion[2] != rtversion[2]) {
        char message[200];
        PyOS_snprintf(message, sizeof(message),
                      "compiletime version %s of module '%.100s' "
                      "does not match runtime version %s",
                      ctversion, __Pyx_MODULE_NAME, rtversion);
        #if PY_VERSION_HEX < 0x02050000
        return PyErr_Warn(NULL, message);
        #else
        return PyErr_WarnEx(NULL, message, 1);
        #endif
    }
    return 0;
}
Exemplo n.º 7
0
QString PythonTransform::help() const
{
    QString help;
    help.append(tr("<p>%1</p>").arg(id));
    help.append(tr("<p>The list of Python transforms is loaded automatically from differents default locations.</p><p>In addition modules are reloaded (refreshed) every time the input is refreshed, so you don't need to restart Pip3line to commit scripts changes</p><p>Using Python %1</p><p>Current Python module name: \"%2\"</p>").arg(QString(Py_GetVersion())).arg(moduleName));
    return help;
}
Exemplo n.º 8
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;
}
Exemplo n.º 9
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 = 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");
}
Exemplo n.º 10
0
int main(int argc, char *argv[])
{
	sys_argc = argc;
	sys_argv = argv;
	origPid = getpid();
	
#ifdef __APPLE__
	extern void install_breakpoint_handlers();
	install_breakpoint_handlers();
#endif
	
	forkExecProc = haveArg("--forkExecProc");
	bool shell = haveArg("--shell");
	bool pyShell = haveArg("--pyshell");
	bool pyExec = haveArg("--pyexec");
	bool noLog = haveArg("--nolog");
	bool help = haveArg("--help") || haveArg("-h");
	bool beingDebugged = AmIBeingDebugged();
	
	const char* logDisabledReason = NULL;
	if(pyShell || pyExec || shell || forkExecProc || help) {} // be quiet
	else if(beingDebugged) {
		logDisabledReason = "debugger detected, not redirecting stdout/stderr";
	}
	else if(noLog) {
		logDisabledReason = "not redirecting stdout/stderr";
	}
	else {
		// current workaround to log stdout/stderr. see http://stackoverflow.com/questions/13104588/how-to-get-stdout-into-console-app
		logEnabled = true;
		printf("MusicPlayer: stdout/stderr goes to %s now\n", logFilename.c_str());
		fflush(stdout);
		int newFd = open(getTildeExpandedPath(logFilename).c_str(), O_WRONLY|O_APPEND|O_CREAT);
		dup2(newFd, fileno(stdout));
		dup2(newFd, fileno(stderr));
		close(newFd);
		//freopen(logFilename.c_str(), "a", stdout);
		//freopen(logFilename.c_str(), "a", stderr);
		stderr = stdout; // well, hack, ... I don't like two seperate buffers. just messes up the output
	}

	if(!forkExecProc) {
		printf("%s", StartupStr);
		install_signal_handler();
	}
	
	if(help) {
		printf(
			   "Help: Available options:\n"
			   "  --nolog		: don't redirect stdout/stderr to log. also implied when run in debugger\n"
			   );
	}

	if(!logEnabled && logDisabledReason)
		printf("%s\n", logDisabledReason);

	std::string mainPyFilename = getResourcePath() + "/Python/main.py";
	Py_SetProgramName(argv[0]);
	if(!forkExecProc)
		printf("Python version: %s, prefix: %s, main: %s\n", Py_GetVersion(), Py_GetPrefix(), mainPyFilename.c_str());
	
	Py_Initialize();
	PyEval_InitThreads();
	addPyPath();

	if(logEnabled) {
		PySys_SetObject((char*)"stdout", PyFile_FromFile(stdout, (char*)"<stdout>", (char*)"w", fclose));
		PySys_SetObject((char*)"stderr", PySys_GetObject((char*)"stdout"));
	}
	PySys_SetObject((char*)"MusicPlayerBin", PyString_FromString(argv[0]));

	// Preload imp and thread. I hope to fix this bug: https://github.com/albertz/music-player/issues/8 , there was a crash in initthread which itself has called initimp
	PyObject* m = NULL;
	m = PyImport_ImportModule("imp");
	Py_XDECREF(m);
	m = PyImport_ImportModule("thread");
	Py_XDECREF(m);
	
	PySys_SetArgvEx(argc, argv, 0);
			
	FILE* fp = fopen((char*)mainPyFilename.c_str(), "r");
	if(fp)
		PyRun_SimpleFile(fp, "main.py");
	else
		printf("Could not open main.py!\n");
	
	if(!forkExecProc && !help && !pyShell && !pyExec && !shell) {
		bool successStartup = checkStartupSuccess();
		if(!successStartup) {
			printf("Error at startup.\n");
			handleFatalError("There was an error at startup.");
		}
	}
	
	return 0;
}
Exemplo n.º 11
0
//---------------------------------------------------------------------------------
// Initializes python.
//---------------------------------------------------------------------------------
bool CPythonManager::Initialize( void )
{
	// Construct a path to the python engine directory.
	char szPythonHome[MAX_GAME_PATH];
	V_snprintf(szPythonHome, MAX_GAME_PATH, "%s/Python3", g_GamePaths.GetSPDir());
	V_FixSlashes(szPythonHome);
	DevMsg(1, "[SP] Python home path set to %s\n", szPythonHome);

	// Convert to wide char for python.
	wchar_t wszPythonHome[1024];
	V_strtowcs(szPythonHome, -1, wszPythonHome, 1024);

	// 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, "Python version %s initialized!\n", Py_GetVersion());

	// 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
	modulsp_init();

	// Import the main module file.
	DevMsg(1, "[SP] Importing main module..\n");
	BEGIN_BOOST_PY()

		python::import("__init__");

	END_BOOST_PY_NORET(); // Noret because we have more stuff to do after this import.

	DevMsg(0, "[Source.Python] Loaded successfully.\n");

	return true;
}
Exemplo n.º 12
0
std::string PySetup::get_version()
{
	return Py_GetVersion();
}
Exemplo n.º 13
0
const char*
python_get_version(void)
{
    return Py_GetVersion();
}
Exemplo n.º 14
0
int uwsgi_python_init() {

#ifndef UWSGI_PYPY
	char *pyversion = strchr(Py_GetVersion(), '\n');
	if (!pyversion) {
        	uwsgi_log_initial("Python version: %s\n", Py_GetVersion());
	}
	else {
        	uwsgi_log_initial("Python version: %.*s %s\n", pyversion-Py_GetVersion(), Py_GetVersion(), Py_GetCompiler()+1);
	}
#else
	uwsgi_log_initial("PyPy version: %s\n", PYPY_VERSION);
#endif

	if (up.home != NULL) {
#ifdef PYTHREE
		wchar_t *wpyhome;
		wpyhome = malloc((sizeof(wchar_t) * strlen(up.home)) + sizeof(wchar_t) );
		if (!wpyhome) {
			uwsgi_error("malloc()");
			exit(1);
		}
		mbstowcs(wpyhome, up.home, strlen(up.home));
		Py_SetPythonHome(wpyhome);
		// do not free this memory !!!
		//free(wpyhome);
#else
		Py_SetPythonHome(up.home);
#endif
		uwsgi_log("Set PythonHome to %s\n", up.home);
	}


#ifdef PYTHREE
	wchar_t pname[6];
	mbstowcs(pname, "uWSGI", 6);
	Py_SetProgramName(pname);
#else
	Py_SetProgramName("uWSGI");
#endif


#ifndef UWSGI_PYPY
	Py_OptimizeFlag = up.optimize;
#endif

	Py_Initialize();

	if (!uwsgi.has_threads) {
		uwsgi_log("*** Python threads support is disabled. You can enable it with --enable-threads ***\n");
	}

	up.wsgi_spitout = PyCFunction_New(uwsgi_spit_method, NULL);
	up.wsgi_writeout = PyCFunction_New(uwsgi_write_method, NULL);

	up.main_thread = PyThreadState_Get();

        // by default set a fake GIL (little impact on performance)
        up.gil_get = gil_fake_get;
        up.gil_release = gil_fake_release;

        up.swap_ts = simple_swap_ts;
        up.reset_ts = simple_reset_ts;
	

	uwsgi_log_initial("Python main interpreter initialized at %p\n", up.main_thread);

	return 1;

}
Exemplo n.º 15
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;
}
Exemplo n.º 16
0
int
Py_FrozenMain(int argc, char **argv)
{
    char *p;
    int i, n, sts;
    int inspect = 0;
    int unbuffered = 0;
    char *oldloc;
    wchar_t **argv_copy = PyMem_Malloc(sizeof(wchar_t*)*argc);
    /* We need a second copies, as Python might modify the first one. */
    wchar_t **argv_copy2 = PyMem_Malloc(sizeof(wchar_t*)*argc);

    Py_FrozenFlag = 1; /* Suppress errors from getpath.c */

    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 (!argv_copy) {
        fprintf(stderr, "out of memory\n");
        return 1;
    }

    oldloc = setlocale(LC_ALL, NULL);
    setlocale(LC_ALL, "");
    for (i = 0; i < argc; i++) {
#ifdef HAVE_BROKEN_MBSTOWCS
        size_t argsize = strlen(argv[i]);
#else
        size_t argsize = mbstowcs(NULL, argv[i], 0);
#endif
        size_t count;
        if (argsize == (size_t)-1) {
            fprintf(stderr, "Could not convert argument %d to string\n", i);
            return 1;
        }
        argv_copy[i] = PyMem_Malloc((argsize+1)*sizeof(wchar_t));
        argv_copy2[i] = argv_copy[i];
        if (!argv_copy[i]) {
            fprintf(stderr, "out of memory\n");
            return 1;
        }
        count = mbstowcs(argv_copy[i], argv[i], argsize+1);
        if (count == (size_t)-1) {
            fprintf(stderr, "Could not convert argument %d to string\n", i);
            return 1;
        }
    }
    setlocale(LC_ALL, oldloc);

#ifdef MS_WINDOWS
    PyInitFrozenExtensions();
#endif /* MS_WINDOWS */
    Py_SetProgramName(argv_copy[0]);
    Py_Initialize();
#ifdef MS_WINDOWS
    PyWinFreeze_ExeInit();
#endif

    if (Py_VerboseFlag)
        fprintf(stderr, "Python %s\n%s\n",
            Py_GetVersion(), Py_GetCopyright());

    PySys_SetArgv(argc, argv_copy);

    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();
    for (i = 0; i < argc; i++) {
        PyMem_Free(argv_copy2[i]);
    }
    PyMem_Free(argv_copy);
    PyMem_Free(argv_copy2);
    return sts;
}
Exemplo n.º 17
0
void
pbs_python_ext_quick_start_interpreter(void)
{
	static char func_id[] = "pbs_python_ext_quick_start_interpreter";

#ifdef	PYTHON           /* -- BEGIN ONLY IF PYTHON IS CONFIGURED -- */

	char pbs_python_home[MAXPATHLEN+1];
	char pbs_python_destlib[MAXPATHLEN+1];

	memset((char *)pbs_python_home, '\0', MAXPATHLEN+1);
	memset((char *)pbs_python_destlib, '\0', MAXPATHLEN+1);

	snprintf(pbs_python_home, MAXPATHLEN, "%s/python",
		pbs_conf.pbs_exec_path);
	snprintf(pbs_python_destlib, MAXPATHLEN, "%s/lib/python/altair",
		pbs_conf.pbs_exec_path);

	Py_NoSiteFlag = 1;
	Py_FrozenFlag = 1;
	Py_OptimizeFlag = 2;            /* TODO make this a compile flag variable */
	Py_IgnoreEnvironmentFlag = 1;   /* ignore PYTHONPATH and PYTHONHOME */
	if (file_exists(pbs_python_home))
		Py_SetPythonHome(pbs_python_home);

	/* we make sure our top level module is initialized */
	if ((PyImport_ExtendInittab(pbs_python_inittab_modules) != 0)) {
		log_err(-1, "PyImport_ExtendInittab",
			"--> Failed to initialize Python interpreter <--");
		return;
	}

	Py_InitializeEx(0);  /* SKIP initialization of signals */

	if (Py_IsInitialized()) {
		snprintf(log_buffer, LOG_BUF_SIZE-1,
			"--> Python Interpreter quick started, compiled with version:'%.*s' <--",
			5, Py_GetVersion());
		log_buffer[LOG_BUF_SIZE-1] = '\0';
		log_event(PBSEVENT_SYSTEM|PBSEVENT_ADMIN |
			PBSEVENT_DEBUG, PBS_EVENTCLASS_SERVER,
			LOG_INFO, func_id, log_buffer);
	} else {
		log_err(-1, "Py_InitializeEx",
			"--> Failed to quick initialize Python interpreter <--");
		goto ERROR_EXIT;
	}
	/*
	 * Add Altair python module directory to sys path. NOTE:
	 *  PBS_PYTHON_MODULE_DIR is a command line define, also insert
	 * standard required python modules
	 */
	if (pbs_python_modify_syspath(pbs_python_destlib, -1) == -1) {
		snprintf(log_buffer, LOG_BUF_SIZE-1,
			"could not insert %s into sys.path shutting down",
			pbs_python_destlib);
		log_buffer[LOG_BUF_SIZE-1] = '\0';
		log_err(-1, func_id, log_buffer);
		goto ERROR_EXIT;
	}

	snprintf(log_buffer, LOG_BUF_SIZE-1,
		"--> Inserted Altair PBS Python modules dir '%s' <--",
		pbs_python_destlib);
	log_buffer[LOG_BUF_SIZE-1] = '\0';
	log_event(PBSEVENT_SYSTEM|PBSEVENT_ADMIN |
		PBSEVENT_DEBUG, PBS_EVENTCLASS_SERVER,
		LOG_INFO, func_id, log_buffer);

	return;

ERROR_EXIT:
	pbs_python_ext_quick_shutdown_interpreter();
	return;
#else   /* !PYTHON */
	log_event(PBSEVENT_SYSTEM|PBSEVENT_ADMIN |
		PBSEVENT_DEBUG, PBS_EVENTCLASS_SERVER,
		LOG_INFO, "start_python",
		"--> Python interpreter not built in <--");
	return;
#endif  /* PYTHON */

}
Exemplo n.º 18
0
int
Py_FrozenMain(int argc, char **argv)
{
    char *p;
    int i, n, sts = 1;
    int inspect = 0;
    int unbuffered = 0;
    char *oldloc = NULL;
    wchar_t **argv_copy = NULL;
    /* We need a second copies, as Python might modify the first one. */
    wchar_t **argv_copy2 = NULL;

    argv_copy = PyMem_RawMalloc(sizeof(wchar_t*) * argc);
    argv_copy2 = PyMem_RawMalloc(sizeof(wchar_t*) * argc);
    if (!argv_copy || !argv_copy2) {
        fprintf(stderr, "out of memory\n");
        goto error;
    }

    Py_FrozenFlag = 1; /* Suppress errors from getpath.c */

    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);
    }

    oldloc = _PyMem_RawStrdup(setlocale(LC_ALL, NULL));
    if (!oldloc) {
        fprintf(stderr, "out of memory\n");
        goto error;
    }

    setlocale(LC_ALL, "");
    for (i = 0; i < argc; i++) {
        argv_copy[i] = _Py_char2wchar(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);
    PyMem_RawFree(oldloc);
    oldloc = NULL;

#ifdef MS_WINDOWS
    PyInitFrozenExtensions();
#endif /* MS_WINDOWS */
    Py_SetProgramName(argv_copy[0]);
    Py_Initialize();
#ifdef MS_WINDOWS
    PyWinFreeze_ExeInit();
#endif

    if (Py_VerboseFlag)
        fprintf(stderr, "Python %s\n%s\n",
            Py_GetVersion(), Py_GetCopyright());

    PySys_SetArgv(argc, argv_copy);

    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();

error:
    PyMem_RawFree(argv_copy);
    if (argv_copy2) {
        for (i = 0; i < argc; i++)
            PyMem_RawFree(argv_copy2[i]);
        PyMem_RawFree(argv_copy2);
    }
    PyMem_RawFree(oldloc);
    return sts;
}
Exemplo n.º 19
0
LRESULT CALLBACK AboutDialog( HWND hwnd, unsigned int msg, WPARAM wparam, LPARAM lparam )
{
	HWND richtext;

	switch ( msg )
	{
	case WM_COMMAND:
		if ( HIWORD( wparam ) == BN_CLICKED && ( HWND ) lparam == GetDlgItem( hwnd, IDOK ) )
		{
			EndDialog( hwnd, 0 );
		}
		break;

	case WM_CLOSE:
		EndDialog( hwnd, 0 );
		break;

	case WM_INITDIALOG:
		richtext = GetDlgItem( hwnd, IDC_RICHEDIT );

		if ( richtext )
		{
			HRSRC resource = FindResource( appInstance, MAKEINTRESOURCE( IDD_CREDITS ), RT_RCDATA );
			HGLOBAL rData = LoadResource( appInstance, resource );

			const char* data = ( const char* ) LockResource( rData );
			QStringList creditList = QStringList::split( ",", data );
			UnlockResource( rData );
			FreeResource( rData );

			CHARRANGE cr;
			CHARFORMAT2 cf;
			ZeroMemory( &cf, sizeof( cf ) );
			cf.cbSize = sizeof( cf );

			// Add a version information header (just like the console)
			QString version = QString( "%1 %2 %3\n" ).arg( productString(), productBeta(), productVersion() );

			cf.dwMask = CFM_COLOR | CFM_WEIGHT | CFM_SIZE;
			cf.yHeight = 20 * 14;
			cf.wWeight = FW_BOLD;
			cf.crTextColor = RGB( 60, 140, 70 );
			SendMessage( richtext, EM_SETCHARFORMAT, SCF_SELECTION, ( LPARAM ) & cf );
			SendMessage( richtext, EM_REPLACESEL, FALSE, ( LPARAM ) version.latin1() );
			cf.dwMask = CFM_COLOR | CFM_WEIGHT | CFM_SIZE;
			cf.yHeight = 20 * 8;
			cf.wWeight = FW_NORMAL;
			cf.crTextColor = RGB( 0, 0, 0 );

			QString credits;
			credits += tr( "Compiled: %1 %2\n" ).arg( __DATE__, __TIME__ );
			credits += tr( "Qt: %1 %2 (Compiled: %3)\n" ).arg( qVersion() ).arg( qSharedBuild() ? "Shared" : "Static" ).arg( QT_VERSION_STR );

			QString pythonBuild = Py_GetVersion();
			pythonBuild = pythonBuild.left( pythonBuild.find( ' ' ) );

#if defined(Py_ENABLE_SHARED)
			credits += tr( "Python: %1 Shared (Compiled: %2)\n" ).arg( pythonBuild ).arg( PY_VERSION );
#else
			credits += tr( "Python: %1 Static (Compiled: %2)\n" ).arg( pythonBuild ).arg( PY_VERSION );
#endif
			credits += tr( "Compiled with SQLite %1\n" ).arg( SQLITE_VERSION );
#if defined (MYSQL_DRIVER)
			credits += tr( "Compiled for MySQL %1 (Using: %2)\n" ).arg( MYSQL_SERVER_VERSION, mysql_get_client_info() );
#else
			credits += tr( "MySQL Support: disabled\n" );
#endif

			cr.cpMin = GetWindowTextLength( richtext );
			cr.cpMax = cr.cpMin;
			SendMessage( richtext, EM_EXSETSEL, 0, ( LPARAM ) & cr );
			SendMessage( richtext, EM_SETCHARFORMAT, SCF_SELECTION, ( LPARAM ) & cf );
			SendMessage( richtext, EM_REPLACESEL, FALSE, ( LPARAM ) credits.latin1() );

			credits = tr( "\nThis is an unsorted and not neccesarily complete list of people who contributed to Wolfpack:\n\n" );

			cr.cpMin = GetWindowTextLength( richtext );
			cr.cpMax = cr.cpMin;
			cf.wWeight = FW_BOLD;
			SendMessage( richtext, EM_EXSETSEL, 0, ( LPARAM ) & cr );
			SendMessage( richtext, EM_SETCHARFORMAT, SCF_SELECTION, ( LPARAM ) & cf );
			SendMessage( richtext, EM_REPLACESEL, FALSE, ( LPARAM ) credits.latin1() );
			cf.wWeight = FW_NORMAL;

			credits = "";
			for ( unsigned int i = 0; i < creditList.size(); ++i )
			{
				credits.append( creditList[i] );
			}

			cr.cpMin = GetWindowTextLength( richtext );
			cr.cpMax = cr.cpMin;
			SendMessage( richtext, EM_EXSETSEL, 0, ( LPARAM ) & cr );
			SendMessage( richtext, EM_SETCHARFORMAT, SCF_SELECTION, ( LPARAM ) & cf );
			SendMessage( richtext, EM_REPLACESEL, FALSE, ( LPARAM ) credits.latin1() );
		}
	}

	return FALSE;
}
Exemplo n.º 20
0
void SCRIPT_API CreateParser(){
    Py_Initialize();
    printf("python %s\n",Py_GetVersion());
}
Exemplo n.º 21
0
int main( int argc, char ** argv )
{
#if defined (FC_OS_LINUX) || defined(FC_OS_BSD)
    // Make sure to setup the Qt locale system before setting LANG and LC_ALL to C.
    // which is needed to use the system locale settings.
    (void)QLocale::system();
#if QT_VERSION < 0x050000
    // http://www.freecadweb.org/tracker/view.php?id=399
    // Because of setting LANG=C the Qt automagic to use the correct encoding
    // for file names is broken. This is a workaround to force the use of UTF-8 encoding
    QFile::setEncodingFunction(myEncoderFunc);
    QFile::setDecodingFunction(myDecoderFunc);
#endif
    // See https://forum.freecadweb.org/viewtopic.php?f=18&t=20600
    // See Gui::Application::runApplication()
    putenv("LC_NUMERIC=C");
    putenv("PYTHONPATH=");
#elif defined(FC_OS_MACOSX)
    (void)QLocale::system();
    putenv("PYTHONPATH=");
#else
    _putenv("PYTHONPATH=");
    // https://forum.freecadweb.org/viewtopic.php?f=4&t=18288
    // https://forum.freecadweb.org/viewtopic.php?f=3&t=20515
    const char* fc_py_home = getenv("FC_PYTHONHOME");
    if (fc_py_home)
        _putenv_s("PYTHONHOME", fc_py_home);
    else
        _putenv("PYTHONHOME=");
#endif

#if defined (FC_OS_WIN32)
    int argc_ = argc;
    QVector<QByteArray> data;
    QVector<char *> argv_;

    // get the command line arguments as unicode string
    {
        QCoreApplication app(argc, argv);
        QStringList args = app.arguments();
        for (QStringList::iterator it = args.begin(); it != args.end(); ++it) {
            data.push_back(it->toUtf8());
            argv_.push_back(data.back().data());
        }
        argv_.push_back(0); // 0-terminated string
    }
#endif

#if PY_MAJOR_VERSION >= 3
#if defined(_MSC_VER) && _MSC_VER <= 1800
    // See InterpreterSingleton::init
    Redirection out(stdout), err(stderr), inp(stdin);
#endif
#endif // PY_MAJOR_VERSION

    // Name and Version of the Application
    App::Application::Config()["ExeName"] = "FreeCAD";
    App::Application::Config()["ExeVendor"] = "FreeCAD";
    App::Application::Config()["AppDataSkipVendor"] = "true";
    App::Application::Config()["MaintainerUrl"] = "http://www.freecadweb.org/wiki/Main_Page";

    // set the banner (for logging and console)
    App::Application::Config()["CopyrightInfo"] = sBanner;
    App::Application::Config()["AppIcon"] = "freecad";
    App::Application::Config()["SplashScreen"] = "freecadsplash";
    App::Application::Config()["StartWorkbench"] = "StartWorkbench";
    //App::Application::Config()["HiddenDockWindow"] = "Property editor";
    App::Application::Config()["SplashAlignment" ] = "Bottom|Left";
    App::Application::Config()["SplashTextColor" ] = "#ffffff"; // white
    App::Application::Config()["SplashInfoColor" ] = "#c8c8c8"; // light grey

    try {
        // Init phase ===========================================================
        // sets the default run mode for FC, starts with gui if not overridden in InitConfig...
        App::Application::Config()["RunMode"] = "Gui";
        App::Application::Config()["Console"] = "0";

        // Inits the Application 
#if defined (FC_OS_WIN32)
        App::Application::init(argc_, argv_.data());
#else
        App::Application::init(argc, argv);
#endif
#if defined(_MSC_VER)
        // create a dump file when the application crashes
        std::string dmpfile = App::Application::getUserAppDataDir();
        dmpfile += "crash.dmp";
        InitMiniDumpWriter(dmpfile);
#endif
        std::map<std::string, std::string>::iterator it = App::Application::Config().find("NavigationStyle");
        if (it != App::Application::Config().end()) {
            ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/View");
            // if not already defined do it now (for the very first start)
            std::string style = hGrp->GetASCII("NavigationStyle", it->second.c_str());
            hGrp->SetASCII("NavigationStyle", style.c_str());
        }

        Gui::Application::initApplication();

        // Only if 'RunMode' is set to 'Gui' do the replacement
        if (App::Application::Config()["RunMode"] == "Gui")
            Base::Interpreter().replaceStdOutput();
    }
    catch (const Base::UnknownProgramOption& e) {
        QApplication app(argc,argv);
        QString appName = QString::fromLatin1(App::Application::Config()["ExeName"].c_str());
        QString msg = QString::fromLatin1(e.what());
        QString s = QLatin1String("<pre>") + msg + QLatin1String("</pre>");
        QMessageBox::critical(0, appName, s);
        exit(1);
    }
    catch (const Base::ProgramInformation& e) {
        QApplication app(argc,argv);
        QString appName = QString::fromLatin1(App::Application::Config()["ExeName"].c_str());
        QString msg = QString::fromUtf8(e.what());
        QString s = QLatin1String("<pre>") + msg + QLatin1String("</pre>");

        QMessageBox msgBox;
        msgBox.setIcon(QMessageBox::Information);
        msgBox.setWindowTitle(appName);
        msgBox.setDetailedText(msg);
        msgBox.setText(s);
        msgBox.exec();
        exit(0);
    }
    catch (const Base::Exception& e) {
        // Popup an own dialog box instead of that one of Windows
        QApplication app(argc,argv);
        QString appName = QString::fromLatin1(App::Application::Config()["ExeName"].c_str());
        QString msg;
        msg = QObject::tr("While initializing %1 the following exception occurred: '%2'\n\n"
                          "Python is searching for its files in the following directories:\n%3\n\n"
                          "Python version information:\n%4\n")
                          .arg(appName).arg(QString::fromUtf8(e.what()))
#if PY_MAJOR_VERSION >= 3
#if PY_MINOR_VERSION >= 5
                          .arg(QString::fromUtf8(Py_EncodeLocale(Py_GetPath(),NULL))).arg(QString::fromLatin1(Py_GetVersion()));
#else
                          .arg(QString::fromUtf8(_Py_wchar2char(Py_GetPath(),NULL))).arg(QString::fromLatin1(Py_GetVersion()));
#endif
#else
                          .arg(QString::fromUtf8(Py_GetPath())).arg(QString::fromLatin1(Py_GetVersion()));
Exemplo n.º 22
0
/*@C
  PetscPythonInitialize - Initialize Python and import petsc4py.

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

  Level: intermediate

.keywords: Python

@*/
PetscErrorCode  PetscPythonInitialize(const char pyexe[],const char pylib[])
{
  PyObject       *module = 0;
  PetscErrorCode ierr;

  PetscFunctionBegin;
  if (PetscBeganPython) PetscFunctionReturn(0);
  /* Python executable */
  if (pyexe && pyexe[0] != 0) {
    ierr = PetscStrncpy(PetscPythonExe,pyexe,sizeof(PetscPythonExe));CHKERRQ(ierr);
  } else {
    ierr = PetscPythonFindExecutable(PetscPythonExe);CHKERRQ(ierr);
  }
  /* Python dynamic library */
  if (pylib && pylib[0] != 0) {
    ierr = PetscStrncpy(PetscPythonLib,pylib,sizeof(PetscPythonLib));CHKERRQ(ierr);
  } else {
    ierr = PetscPythonFindLibrary(PetscPythonExe,PetscPythonLib);CHKERRQ(ierr);
  }
  /* dynamically load Python library */
  ierr = PetscPythonLoadLibrary(PetscPythonLib);CHKERRQ(ierr);
  /* initialize Python */
  PetscBeganPython = PETSC_FALSE;
  if (!Py_IsInitialized()) {
    static PetscBool registered = PETSC_FALSE;
    const char       *py_version;
    PyObject         *sys_path;
    char             path[PETSC_MAX_PATH_LEN] = { 0 };

    /* initialize Python */
    Py_InitializeEx(0); /* 0: do not install signal handlers */
    /*  build 'sys.argv' list */
    py_version = Py_GetVersion();
    if (py_version[0] == '2') {
      int argc = 0; char **argv = 0;
      ierr = PetscGetArgs(&argc,&argv);CHKERRQ(ierr);
      PySys_SetArgv(argc,argv);
    }
    if (py_version[0] == '3') {
      /* XXX 'argv' is type 'wchar_t**' */
      PySys_SetArgv(0,NULL);
    }
    /* add PETSC_LIB_DIR in front of 'sys.path' */
    sys_path = PySys_GetObject("path");
    if (sys_path) {
      ierr = PetscStrreplace(PETSC_COMM_SELF,"${PETSC_LIB_DIR}",path,sizeof(path));CHKERRQ(ierr);
      Py_DecRef(PyObject_CallMethod(sys_path,"insert","is",(int)0,(char*)path));
    }
    /* register finalizer */
    if (!registered) {
      ierr = PetscRegisterFinalize(PetscPythonFinalize);CHKERRQ(ierr);

      registered = PETSC_TRUE;
    }
    PetscBeganPython = PETSC_TRUE;
  }
  /* import 'petsc4py.PETSc' module */
  module = PyImport_ImportModule("petsc4py.PETSc");
  if (module) {
    ierr = PetscInfo(0,"Python: successfully imported  module 'petsc4py.PETSc'\n");CHKERRQ(ierr);

    Py_DecRef(module); module = 0;
  } else {
    PetscPythonPrintError();
    SETERRQ(PETSC_COMM_SELF,PETSC_ERR_PLIB,"Python: could not import module 'petsc4py.PETSc', perhaps your PYTHONPATH does not contain it\n");
  }
  PetscFunctionReturn(0);
}
Exemplo n.º 23
0
void
pbs_python_ext_start_interpreter(
	struct python_interpreter_data *interp_data)
{
	static char func_id[] = "pbs_python_ext_start_interpreter";

#ifdef	PYTHON           /* -- BEGIN ONLY IF PYTHON IS CONFIGURED -- */

	struct stat sbuf;
	char pbs_python_home[MAXPATHLEN+1];
	char pbs_python_destlib[MAXPATHLEN+1];
	int  evtype;
	int  rc;

	/*
	 * initialize the convenience global pbs_python_daemon_name, as it is
	 * used everywhere
	 */

	pbs_python_daemon_name = interp_data->daemon_name;

	/* Need to make logging less verbose if pbs_python command */
	/* used, since it can get called many times in a pbs daemon, */
	/* and it would litter that daemon's logs */
	if (IS_PBS_PYTHON_CMD(pbs_python_daemon_name))
		evtype = PBSEVENT_DEBUG3;
	else
		evtype = PBSEVENT_DEBUG2;

	memset((char *)pbs_python_home, '\0', MAXPATHLEN+1);
	memset((char *)pbs_python_destlib, '\0', MAXPATHLEN+1);

	snprintf(pbs_python_home, MAXPATHLEN, "%s/python",
		pbs_conf.pbs_exec_path);
	snprintf(pbs_python_destlib, MAXPATHLEN, "%s/lib64/python/altair",
		pbs_conf.pbs_exec_path);
	rc = stat(pbs_python_destlib, &sbuf);
	if (rc != 0) {
		snprintf(pbs_python_destlib, MAXPATHLEN, "%s/lib/python/altair",
			pbs_conf.pbs_exec_path);
		rc = stat(pbs_python_destlib, &sbuf);
	}
	if (rc != 0) {
		log_err(-1, func_id,
			"--> PBS Python library directory not found <--");
		return;
	}
	if (!S_ISDIR(sbuf.st_mode)) {
		log_err(-1, func_id,
			"--> PBS Python library path is not a directory <--");
		return;
	}

	if (interp_data) {
		interp_data->init_interpreter_data(interp_data); /* to be safe */
		if (interp_data->interp_started) {
			log_event(evtype, PBS_EVENTCLASS_SERVER,
				LOG_INFO, interp_data->daemon_name,
				"--> Python interpreter already started <--");
			return;
		}
	} else { /* we need to allocate memory */
		log_err(-1, func_id,
			"--> Passed NULL for interpreter data <--");
		return;
	}

	Py_NoSiteFlag = 1;
	Py_FrozenFlag = 1;
	Py_OptimizeFlag = 2;            /* TODO make this a compile flag variable */
	Py_IgnoreEnvironmentFlag = 1;   /* ignore PYTHONPATH and PYTHONHOME */
	if (file_exists(pbs_python_home))
		Py_SetPythonHome(pbs_python_home);

	/* we make sure our top level module is initialized */
	if ((PyImport_ExtendInittab(pbs_python_inittab_modules) != 0)) {
		log_err(-1, "PyImport_ExtendInittab",
			"--> Failed to initialize Python interpreter <--");
		return;
	}


	Py_InitializeEx(1);  /* arg '1' means to not skip init of signals -    */
	/* we want signals to propagate to the executing  */
	/* Python script to be able to interrupt it       */

	if (Py_IsInitialized()) {
		interp_data->interp_started = 1; /* mark python as initialized */
		/* print only the first five characters, TODO check for NULL? */
		snprintf(log_buffer, LOG_BUF_SIZE-1,
			"--> Python Interpreter started, compiled with version:'%.*s' <--",
			5, Py_GetVersion());
		log_buffer[LOG_BUF_SIZE-1] = '\0';
		log_event(evtype, PBS_EVENTCLASS_SERVER,
			LOG_INFO, interp_data->daemon_name, log_buffer);
	} else {
		log_err(-1, "Py_InitializeEx",
			"--> Failed to initialize Python interpreter <--");
		goto ERROR_EXIT;
	}
	/*
	 * Add Altair python module directory to sys path. NOTE:
	 *  PBS_PYTHON_MODULE_DIR is a command line define, also insert
	 * standard required python modules
	 */
	if (pbs_python_modify_syspath(pbs_python_destlib, -1) == -1) {
		snprintf(log_buffer, LOG_BUF_SIZE-1,
			"could not insert %s into sys.path shutting down",
			pbs_python_destlib);
		log_buffer[LOG_BUF_SIZE-1] = '\0';
		log_err(-1, func_id, log_buffer);
		goto ERROR_EXIT;
	}

	/*
	 * At this point it is safe to load the available server types from
	 * the python modules. since the syspath is setup correctly
	 */
	if ((pbs_python_load_python_types(interp_data) == -1)) {
		log_err(-1, func_id, "could not load python types into the interpreter");
		goto ERROR_EXIT;
	}

	interp_data->pbs_python_types_loaded = 1; /* just in case */
	return;

ERROR_EXIT:
	pbs_python_ext_shutdown_interpreter(interp_data);
	return;
#else  /* !PYTHON */
	log_event(PBSEVENT_SYSTEM|PBSEVENT_ADMIN |
		PBSEVENT_DEBUG, PBS_EVENTCLASS_SERVER,
		LOG_INFO, "start_python",
		"--> Python interpreter not built in <--");
	return;
#endif /* PYTHON */
}
Exemplo n.º 24
0
void pybase::lib_setup()
{   
    post("");
    post("------------------------------------------------");
    post("py/pyext %s - python script objects",PY__VERSION);
    post("(C)2002-2015 Thomas Grill - http://grrrr.org/ext");
    post("");
    post("using Python %s",Py_GetVersion());

#ifdef FLEXT_DEBUG
    post("");
    post("DEBUG version compiled on %s %s",__DATE__,__TIME__);
#endif

    // -------------------------------------------------------------

    sym_response = flext::MakeSymbol("response");

#if FLEXT_SYS == FLEXT_SYS_PD
    sym_fint = sym_float;
#else
    sym_fint = sym_int;
#endif

    // -------------------------------------------------------------

    Py_Initialize();

#ifdef FLEXT_DEBUG
//  Py_DebugFlag = 1;
//  Py_VerboseFlag = 1;
#else
    Py_OptimizeFlag = 1;
#endif

#ifdef FLEXT_THREADS
    // enable thread support and acquire the global thread lock
    PyEval_InitThreads();

#ifndef PY_USE_GIL
    // get thread state
    pythrsys = PyThreadState_Get();
    // get main interpreter state
    pymain = pythrsys->interp;

    // add thread state of main thread to map
    pythrmap[GetThreadId()] = pythrsys;
#endif // PY_USE_GIL

#endif

    // sys.argv must be set to empty tuple
    const char *nothing = "";
    PySys_SetArgv(0,const_cast<char **>(&nothing));

    // register/initialize pyext module only once!
    module_obj = Py_InitModule(const_cast<char *>(PYEXT_MODULE), func_tbl);
    module_dict = PyModule_GetDict(module_obj); // borrowed reference

    PyModule_AddStringConstant(module_obj,"__doc__",(char *)py_doc);

    // redirect stdout
    PyObject* py_out;
    py_out = Py_InitModule(const_cast<char *>("stdout"), StdOut_Methods);
    PySys_SetObject(const_cast<char *>("stdout"), py_out);
    py_out = Py_InitModule(const_cast<char *>("stderr"), StdOut_Methods);
    PySys_SetObject(const_cast<char *>("stderr"), py_out);

    // get garbage collector function
    PyObject *gcobj = PyImport_ImportModule("gc");
    if(gcobj) {
        gcollect = PyObject_GetAttrString(gcobj,"collect");
        Py_DECREF(gcobj);
    }

    builtins_obj = PyImport_ImportModule("__builtin__");
    builtins_dict = PyModule_GetDict(builtins_obj); // borrowed reference

    // add symbol type
    initsymbol();
    PyModule_AddObject(module_obj,"Symbol",(PyObject *)&pySymbol_Type);

    // pre-defined symbols
    PyModule_AddObject(module_obj,"_s_",(PyObject *)pySymbol__);
    PyModule_AddObject(module_obj,"_s_bang",(PyObject *)pySymbol_bang);
    PyModule_AddObject(module_obj,"_s_list",(PyObject *)pySymbol_list);
    PyModule_AddObject(module_obj,"_s_symbol",(PyObject *)pySymbol_symbol);
    PyModule_AddObject(module_obj,"_s_float",(PyObject *)pySymbol_float);
    PyModule_AddObject(module_obj,"_s_int",(PyObject *)pySymbol_int);

    // add samplebuffer type
    initsamplebuffer();
    PyModule_AddObject(module_obj,"Buffer",(PyObject *)&pySamplebuffer_Type);

    // add message bundle type
    initbundle();
    PyModule_AddObject(module_obj,"Bundle",(PyObject *)&pyBundle_Type);

    // -------------------------------------------------------------
#if FLEXT_SYS == FLEXT_SYS_PD && defined(PD_DEVEL_VERSION) && defined(PY_USE_INOFFICIAL)
    // add PD paths

    char *dir;
    for(int i = 0; (dir = namelist_get(sys_searchpath,i)) != NULL; ++i) {
        AddToPath(dir);
    }
#endif
    // -------------------------------------------------------------

    FLEXT_SETUP(pyobj);
    FLEXT_SETUP(pymeth);
    FLEXT_SETUP(pyext);
#ifndef PY_NODSP
    FLEXT_DSP_SETUP(pydsp);
#endif

#ifdef FLEXT_THREADS
    // release global lock
    PyEval_ReleaseLock();

    // launch thread worker
    LaunchThread(quworker,NULL);

    // launch python worker
    LaunchThread(pyworker,NULL);
#endif

    post("------------------------------------------------");
    post("");
}
Exemplo n.º 25
0
int main( int argc, char ** argv )
{
#if defined (FC_OS_LINUX) || defined(FC_OS_BSD)
    // Make sure to setup the Qt locale system before setting LANG and LC_ALL to C.
    // which is needed to use the system locale settings.
    (void)QLocale::system();
    // http://www.freecadweb.org/tracker/view.php?id=399
    // Because of setting LANG=C the Qt automagic to use the correct encoding
    // for file names is broken. This is a workaround to force the use of UTF-8 encoding
    QFile::setEncodingFunction(myEncoderFunc);
    QFile::setDecodingFunction(myDecoderFunc);
    // Make sure that we use '.' as decimal point. See also
    // http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=559846
    putenv("LC_NUMERIC=C");
    putenv("PYTHONPATH=");
#elif defined(FC_OS_MACOSX)
    (void)QLocale::system();
    putenv("LC_NUMERIC=C");
    putenv("PYTHONPATH=");
#else
    setlocale(LC_NUMERIC, "C");
    _putenv("PYTHONPATH=");
#endif

#if defined (FC_OS_WIN32)
    int argc_ = argc;
    QVector<QByteArray> data;
    QVector<char *> argv_;

    // get the command line arguments as unicode string
    {
        QCoreApplication app(argc, argv);
        QStringList args = app.arguments();
        for (QStringList::iterator it = args.begin(); it != args.end(); ++it) {
            data.push_back(it->toUtf8());
            argv_.push_back(data.back().data());
        }
        argv_.push_back(0); // 0-terminated string
    }
#endif

    // Name and Version of the Application
    App::Application::Config()["ExeName"] = "FreeCAD";
    App::Application::Config()["ExeVendor"] = "FreeCAD";
    App::Application::Config()["AppDataSkipVendor"] = "true";
    App::Application::Config()["MaintainerUrl"] = "http://www.freecadweb.org/wiki/index.php?title=Main_Page";

    // set the banner (for logging and console)
    App::Application::Config()["CopyrightInfo"] = sBanner;
    App::Application::Config()["AppIcon"] = "freecad";
    App::Application::Config()["SplashScreen"] = "freecadsplash";
    App::Application::Config()["StartWorkbench"] = "StartWorkbench";
    //App::Application::Config()["HiddenDockWindow"] = "Property editor";
    App::Application::Config()["SplashAlignment" ] = "Bottom|Left";
    App::Application::Config()["SplashTextColor" ] = "#ffffff"; // white
    App::Application::Config()["SplashInfoColor" ] = "#c8c8c8"; // light grey

    try {
        // Init phase ===========================================================
        // sets the default run mode for FC, starts with gui if not overridden in InitConfig...
        App::Application::Config()["RunMode"] = "Gui";

        // Inits the Application 
#if defined (FC_OS_WIN32)
        App::Application::init(argc_, argv_.data());
#else
        App::Application::init(argc, argv);
#endif
#if defined(_MSC_VER)
        // create a dump file when the application crashes
        std::string dmpfile = App::Application::getUserAppDataDir();
        dmpfile += "crash.dmp";
        InitMiniDumpWriter(dmpfile);
#endif
        std::map<std::string, std::string>::iterator it = App::Application::Config().find("NavigationStyle");
        if (it != App::Application::Config().end()) {
            ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/View");
            // if not already defined do it now (for the very first start)
            std::string style = hGrp->GetASCII("NavigationStyle", it->second.c_str());
            hGrp->SetASCII("NavigationStyle", style.c_str());
        }

        Gui::Application::initApplication();

        // Only if 'RunMode' is set to 'Gui' do the replacement
        if (App::Application::Config()["RunMode"] == "Gui")
            Base::Interpreter().replaceStdOutput();
    }
    catch (const Base::UnknownProgramOption& e) {
        QApplication app(argc,argv);
        QString appName = QString::fromAscii(App::Application::Config()["ExeName"].c_str());
        QString msg = QString::fromAscii(e.what());
        QString s = QLatin1String("<pre>") + msg + QLatin1String("</pre>");
        QMessageBox::critical(0, appName, s);
        exit(1);
    }
    catch (const Base::ProgramInformation& e) {
        QApplication app(argc,argv);
        QString appName = QString::fromAscii(App::Application::Config()["ExeName"].c_str());
        QString msg = QString::fromAscii(e.what());
        QString s = QLatin1String("<pre>") + msg + QLatin1String("</pre>");
        QMessageBox::information(0, appName, s);
        exit(0);
    }
    catch (const Base::Exception& e) {
        // Popup an own dialog box instead of that one of Windows
        QApplication app(argc,argv);
        QString appName = QString::fromAscii(App::Application::Config()["ExeName"].c_str());
        QString msg;
        msg = QObject::tr("While initializing %1 the  following exception occurred: '%2'\n\n"
                          "Python is searching for its files in the following directories:\n%3\n\n"
                          "Python version information:\n%4\n")
                          .arg(appName).arg(QString::fromUtf8(e.what()))
                          .arg(QString::fromUtf8(Py_GetPath())).arg(QString::fromAscii(Py_GetVersion()));
        const char* pythonhome = getenv("PYTHONHOME");
        if (pythonhome) {
            msg += QObject::tr("\nThe environment variable PYTHONHOME is set to '%1'.")
                .arg(QString::fromUtf8(pythonhome));
            msg += QObject::tr("\nSetting this environment variable might cause Python to fail. "
                "Please contact your administrator to unset it on your system.\n\n");
        } else {
            msg += QObject::tr("\nPlease contact the application's support team for more information.\n\n");
        }

        QMessageBox::critical(0, QObject::tr("Initialization of %1 failed").arg(appName), msg);
        exit(100);
    }
    catch (...) {
        // Popup an own dialog box instead of that one of Windows
        QApplication app(argc,argv);
        QString appName = QString::fromAscii(App::Application::Config()["ExeName"].c_str());
        QString msg = QObject::tr("Unknown runtime error occurred while initializing %1.\n\n"
                                  "Please contact the application's support team for more information.\n\n").arg(appName);
        QMessageBox::critical(0, QObject::tr("Initialization of %1 failed").arg(appName), msg);
        exit(101);
    }

    // Run phase ===========================================================
    Base::RedirectStdOutput stdcout;
    Base::RedirectStdLog    stdclog;
    Base::RedirectStdError  stdcerr;
    std::streambuf* oldcout = std::cout.rdbuf(&stdcout);
    std::streambuf* oldclog = std::clog.rdbuf(&stdclog);
    std::streambuf* oldcerr = std::cerr.rdbuf(&stdcerr);

    try {
        if (App::Application::Config()["RunMode"] == "Gui")
            Gui::Application::runApplication();
        else
            App::Application::runApplication();
    }
    catch (const Base::SystemExitException&) {
        exit(0);
    }
    catch (const Base::Exception& e) {
        Base::Console().Error("%s\n", e.what());
    }
    catch (...) {
        Base::Console().Error("Application unexpectedly terminated\n");
    }

    std::cout.rdbuf(oldcout);
    std::clog.rdbuf(oldclog);
    std::cerr.rdbuf(oldcerr);

    // Destruction phase ===========================================================
    Base::Console().Log("%s terminating...\n",App::Application::Config()["ExeName"].c_str());

    // cleans up 
    App::Application::destruct();

    Base::Console().Log("%s completely terminated\n",App::Application::Config()["ExeName"].c_str());

    return 0;
}
Exemplo n.º 26
0
/*
 * Class:     org_jpy_PyLib
 * Method:    startPython0
 * Signature: ([Ljava/lang/String;)Z
 */
JNIEXPORT jboolean JNICALL Java_org_jpy_PyLib_startPython0
  (JNIEnv* jenv, jclass jLibClass, jobjectArray jPathArray)
{
    int pyInit = Py_IsInitialized();

    JPy_DIAG_PRINT(JPy_DIAG_F_ALL, "PyLib_startPython: entered: jenv=%p, pyInit=%d, JPy_Module=%p\n", jenv, pyInit, JPy_Module);

    if (!pyInit) {
        Py_Initialize();
        PyLib_RedirectStdOut();
        pyInit = Py_IsInitialized();
    }

    if (pyInit) {

        if (JPy_DiagFlags != 0) {
            printf("PyLib_startPython: global Python interpreter information:\n");
            #if defined(JPY_COMPAT_33P)
            printf("  Py_GetProgramName()     = \"%ls\"\n", Py_GetProgramName());
            printf("  Py_GetPrefix()          = \"%ls\"\n", Py_GetPrefix());
            printf("  Py_GetExecPrefix()      = \"%ls\"\n", Py_GetExecPrefix());
            printf("  Py_GetProgramFullPath() = \"%ls\"\n", Py_GetProgramFullPath());
            printf("  Py_GetPath()            = \"%ls\"\n", Py_GetPath());
            printf("  Py_GetPythonHome()      = \"%ls\"\n", Py_GetPythonHome());
            #elif defined(JPY_COMPAT_27)
            printf("  Py_GetProgramName()     = \"%s\"\n", Py_GetProgramName());
            printf("  Py_GetPrefix()          = \"%s\"\n", Py_GetPrefix());
            printf("  Py_GetExecPrefix()      = \"%s\"\n", Py_GetExecPrefix());
            printf("  Py_GetProgramFullPath() = \"%s\"\n", Py_GetProgramFullPath());
            printf("  Py_GetPath()            = \"%s\"\n", Py_GetPath());
            printf("  Py_GetPythonHome()      = \"%s\"\n", Py_GetPythonHome());
            #endif
            printf("  Py_GetVersion()         = \"%s\"\n", Py_GetVersion());
            printf("  Py_GetPlatform()        = \"%s\"\n", Py_GetPlatform());
            printf("  Py_GetCompiler()        = \"%s\"\n", Py_GetCompiler());
            printf("  Py_GetBuildInfo()       = \"%s\"\n", Py_GetBuildInfo());
        }

        // If we've got jPathArray, add all entries to Python's "sys.path"
        //
        if (jPathArray != NULL) {
            PyObject* pyPathList;
            PyObject* pyPath;
            jstring jPath;
            jsize i, pathCount;

            pathCount = (*jenv)->GetArrayLength(jenv, jPathArray);
            //printf(">> pathCount=%d\n", pathCount);
            if (pathCount > 0) {

                JPy_BEGIN_GIL_STATE

                pyPathList = PySys_GetObject("path");
                //printf(">> pyPathList=%p, len=%ld\n", pyPathList, PyList_Size(pyPathList));
                if (pyPathList != NULL) {
                    Py_INCREF(pyPathList);
                    for (i = pathCount - 1; i >= 0; i--) {
                        jPath = (*jenv)->GetObjectArrayElement(jenv, jPathArray, i);
                        //printf(">> i=%d, jPath=%p\n", i, jPath);
                        if (jPath != NULL) {
                            pyPath = JPy_FromJString(jenv, jPath);
                            //printf(">> i=%d, pyPath=%p\n", i, pyPath);
                            if (pyPath != NULL) {
                                PyList_Insert(pyPathList, 0, pyPath);
                            }
                        }
                    }
                    Py_DECREF(pyPathList);
                }
                //printf(">> pyPathList=%p, len=%ld\n", pyPathList, PyList_Size(pyPathList));
                //printf(">> pyPathList=%p, len=%ld (check)\n", PySys_GetObject("path"), PyList_Size(PySys_GetObject("path")));

                JPy_END_GIL_STATE
            }
        }
Exemplo n.º 27
0
int
Py_FrozenMain(int argc, char **argv)
{
    _PyInitError err = _PyRuntime_Initialize();
    if (_Py_INIT_FAILED(err)) {
        fprintf(stderr, "Fatal Python error: %s\n", err.msg);
        fflush(stderr);
        exit(1);
    }

    const char *p;
    int i, n, sts = 1;
    int inspect = 0;
    int unbuffered = 0;
    char *oldloc = NULL;
    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 = PyMem_RawMalloc(sizeof(wchar_t*) * argc);
        argv_copy2 = PyMem_RawMalloc(sizeof(wchar_t*) * argc);
        if (!argv_copy || !argv_copy2) {
            fprintf(stderr, "out of memory\n");
            goto error;
        }
    }

    _PyCoreConfig config = _PyCoreConfig_INIT;
    config._frozen = 1;   /* Suppress errors from getpath.c */

    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);
    }

    oldloc = _PyMem_RawStrdup(setlocale(LC_ALL, NULL));
    if (!oldloc) {
        fprintf(stderr, "out of memory\n");
        goto error;
    }

    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);
    PyMem_RawFree(oldloc);
    oldloc = NULL;

#ifdef MS_WINDOWS
    PyInitFrozenExtensions();
#endif /* MS_WINDOWS */
    if (argc >= 1)
        Py_SetProgramName(argv_copy[0]);

    err = _Py_InitializeFromConfig(&config);
    /* No need to call _PyCoreConfig_Clear() since we didn't allocate any
       memory: program_name is a constant string. */
    if (_Py_INIT_FAILED(err)) {
        _Py_FatalInitError(err);
    }

#ifdef MS_WINDOWS
    PyWinFreeze_ExeInit();
#endif

    if (Py_VerboseFlag)
        fprintf(stderr, "Python %s\n%s\n",
            Py_GetVersion(), Py_GetCopyright());

    PySys_SetArgv(argc, argv_copy);

    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
    if (Py_FinalizeEx() < 0) {
        sts = 120;
    }

error:
    PyMem_RawFree(argv_copy);
    if (argv_copy2) {
        for (i = 0; i < argc; i++)
            PyMem_RawFree(argv_copy2[i]);
        PyMem_RawFree(argv_copy2);
    }
    PyMem_RawFree(oldloc);
    return sts;
}
Exemplo n.º 28
0
static void smisk_crash_sighandler(int signum, siginfo_t* info, void*ptr) {
  FILE *out = NULL;
  char out_fn[PATH_MAX];
  char cwd_buf[PATH_MAX];
  char *cwd = NULL;
  struct tm *t;
  time_t timer;
  size_t i = 0;
  const char *found_gdb_path;
  char cmd[1024];
  // Signal code table (from http://www.opengroup.org/onlinepubs/007908799/xsh/signal.h.html)
  static const char *si_codes[][9] = {
    {"", "", "", "", "", "", "", "", ""},
    {"", "", "", "", "", "", "", "", ""},
    {"", "", "", "", "", "", "", "", ""},
    {"",
     "ILL_ILLOPC\tillegal opcode",
     "ILL_ILLOPN\tillegal operand",
     "ILL_ILLADR\tillegal addressing mode",
     "ILL_ILLTRP\tillegal trap",
     "ILL_PRVOPC\tprivileged opcode",
     "ILL_PRVREG\tprivileged register",
     "ILL_COPROC\tcoprocessor error",
     "ILL_BADSTK\tinternal stack error"}, // ILL
    {"", "", "", "", "", "", "", "", ""},
    {"", "", "", "", "", "", "", "", ""},
    {"", "", "", "", "", "", "", "", ""},
    {"",
     "FPE_INTDIV\tinteger divide by zero",
     "FPE_INTOVF\tinteger overflow", 
     "FPE_FLTDIV\tfloating point divide by zero",
     "FPE_FLTOVF\tfloating point overflow",
     "FPE_FLTUND\tfloating point underflow",
     "FPE_FLTRES\tfloating point inexact result",
     "FPE_FLTINV\tinvalid floating point operation",
     "FPE_FLTSUB\tsubscript out of range"}, // FPE
    {"", "", "", "", "", "", "", "", ""},
    {"",
     "BUS_ADRALN\tinvalid address alignment",
     "BUS_ADRERR\tnon-existent physical address",
     "BUS_OBJERR\tobject specific hardware error",
     "", "", "", ""}, // BUS
    {"",
     "SEGV_MAPERR\taddress not mapped to object",
     "SEGV_ACCERR\tinvalid permissions for mapped object",
     "", "", "", "", "", ""} // SEGV
  };
  // Possible paths to GDB
  static const char *gdb_path[] = {
    "/usr/bin/gdb",
    "/usr/local/bin/gdb",
    "/opt/local/bin/gdb",
    "/opt/bin/gdb",
    "/local/bin/gdb",
    NULL
  };
  
  // Header
  fputs("FATAL: smisk died from ", stderr);
  switch(signum) {
    case SIGILL:
      fputs("Illegal instruction ", stderr);
      break;
    case SIGFPE:
      fputs("Floating-point exception ", stderr);
      break;
    case SIGBUS:
      fputs("Bus error ", stderr);
      break;
    case SIGSEGV:
      fputs("Segmentation violation ", stderr);
      break;
  }
  fprintf(stderr, "[%d] ", signum);
  fflush(stderr);
  
  // Construct filename smisk-YYYYMMDD-HHMMSS.PID.crash
  timer = time(NULL);
  t = localtime(&timer);
  cwd = getcwd(cwd_buf, PATH_MAX);
  sprintf(out_fn, "%s/smisk-%04d%02d%02d-%02d%02d%02d.%d.crash",
    (access(cwd ? cwd : ".", W_OK) == 0) ? (cwd ? cwd : ".") : "/tmp",
    1900+t->tm_year, t->tm_mon+1, t->tm_mday, t->tm_hour, t->tm_min, t->tm_sec, getpid());
  
  // Open file
  fprintf(stderr, "Writing crash dump to %s...\n", out_fn);
  out = fopen(out_fn, "w");
  if (!out)
    out = stderr;
  
  // Basic info
  fprintf(out, "Time:               %04d-%02d-%02d %02d:%02d:%02d\n",
    1900+t->tm_year, t->tm_mon+1, t->tm_mday, t->tm_hour, t->tm_min, t->tm_sec);
  fprintf(out, "Process:            %d\n", getpid());
  fprintf(out, "Working directory:  %s\n", cwd ? cwd : "?");
  fprintf(out, "Python:             %s %s\n", Py_GetProgramFullPath(), Py_GetVersion());
  fprintf(out, "Smisk:              %s (%s)\n", SMISK_VERSION, SMISK_BUILD_ID);
  #if HAVE_SYS_UTSNAME_H
    struct utsname un;
    if (uname(&un) == 0) {
      fprintf(out, "System:             %s, %s, %s, %s\n",
        un.sysname, un.release, un.version, un.machine);
      fprintf(out, "Hostname:           %s\n", un.nodename);
    }
    else
  #endif
    fprintf(out, "System:             %s\n", Py_GetPlatform());
  fprintf(out, "\n");
  fprintf(out, "Signal:             %d\n", signum);
  fprintf(out, "Errno:              %d\n", info->si_errno);
  fprintf(out, "Code:               %d\t%s\n", info->si_code, (signum > 0) ? si_codes[signum-1][info->si_code] : "?");
  fprintf(out, "Address:            %p\n", info->si_addr);
  
  // Find GDB
  i = 0;
  found_gdb_path = NULL;
  do {
    if (access(*(gdb_path+i), R_OK) == 0) {
      found_gdb_path = *(gdb_path+i);
      log_debug("found gdb at %s", found_gdb_path);
      break;
    }
  } while ( *(gdb_path + ++i) );
  
  // Write backtrace
  fprintf(out, "\nBacktrace:\n");
  if (found_gdb_path) {
    fclose(out);
    system("/bin/echo 'backtrace' > /tmp/smisk_gdb_args");
    sprintf(cmd, "%s -batch -x /tmp/smisk_gdb_args %s %d >> %s",
      found_gdb_path, Py_GetProgramFullPath(), getpid(), out_fn);
    system(cmd);
  }
  else {
    log_error("Note: GDB not found. Install GDB to get a more detailed backtrace.");
    smisk_crash_write_backtrace(info, ptr, out);
    fclose(out);
  }
  
  //exit(-1);
  _exit(-1);
}