static _PyInitError calculate_init(PyCalculatePath *calculate, const _PyCoreConfig *core_config) { size_t len; const char *path = getenv("PATH"); if (path) { calculate->path_env = Py_DecodeLocale(path, &len); if (!calculate->path_env) { return DECODE_LOCALE_ERR("PATH environment variable", len); } } calculate->pythonpath = Py_DecodeLocale(PYTHONPATH, &len); if (!calculate->pythonpath) { return DECODE_LOCALE_ERR("PYTHONPATH define", len); } calculate->prefix = Py_DecodeLocale(PREFIX, &len); if (!calculate->prefix) { return DECODE_LOCALE_ERR("PREFIX define", len); } calculate->exec_prefix = Py_DecodeLocale(EXEC_PREFIX, &len); if (!calculate->prefix) { return DECODE_LOCALE_ERR("EXEC_PREFIX define", len); } calculate->lib_python = Py_DecodeLocale("lib/python" VERSION, &len); if (!calculate->lib_python) { return DECODE_LOCALE_ERR("EXEC_PREFIX define", len); } return _Py_INIT_OK(); }
PyObject* getFileData(int argc, char *argv[]) { PyObject *BioModule = PyImport_ImportModule("Bio"); const char *filename, *filetype, *pycmdToRun; filename = (const char *)PyUnicode_DecodeFSDefault(argv[1]); filetype = (const char *)PyUnicode_DecodeFSDefault(argv[2]); std::string cmdToRun = "import Bio\nBio.SeqIO.parse("; cmdToRun = cmdToRun + filename + std::string(",") + filetype; pycmdToRun = cmdToRun.c_str(); wchar_t *program = Py_DecodeLocale(argv[0], NULL); if (program == NULL) { fprintf(stderr, "Fatal error: cannot decode argv[0]\n"); exit(1); } Py_SetProgramName(program); /* optional but recommended */ Py_Initialize(); PyObject* filedata; filedata = PyRun_String(pycmdToRun, 0, NULL, NULL); Py_DECREF(filename); Py_DECREF(filetype); Py_Finalize(); PyMem_RawFree(program); return filedata; }
int python_main(int argc, char **argv) { wchar_t **argv_copy; /* We need a second copy, as Python might modify the first one. */ wchar_t **argv_copy2; int i, res; char *oldloc; #ifdef __FreeBSD__ fp_except_t m; #endif argv_copy = (wchar_t **)PyMem_RawMalloc(sizeof(wchar_t*) * (argc+1)); argv_copy2 = (wchar_t **)PyMem_RawMalloc(sizeof(wchar_t*) * (argc+1)); if (!argv_copy || !argv_copy2) { fprintf(stderr, "out of memory\n"); return 1; } /* 754 requires that FP exceptions run in "no stop" mode by default, * and until C vendors implement C99's ways to control FP exceptions, * Python requires non-stop mode. Alas, some platforms enable FP * exceptions by default. Here we disable them. */ #ifdef __FreeBSD__ m = fpgetmask(); fpsetmask(m & ~FP_X_OFL); #endif oldloc = _PyMem_RawStrdup(setlocale(LC_ALL, NULL)); if (!oldloc) { fprintf(stderr, "out of memory\n"); return 1; } setlocale(LC_ALL, ""); for (i = 0; i < argc; i++) { argv_copy[i] = Py_DecodeLocale(argv[i], NULL); if (!argv_copy[i]) { PyMem_RawFree(oldloc); fprintf(stderr, "Fatal Python error: " "unable to decode the command line argument #%i\n", i + 1); return 1; } argv_copy2[i] = argv_copy[i]; } argv_copy2[argc] = argv_copy[argc] = NULL; setlocale(LC_ALL, oldloc); PyMem_RawFree(oldloc); res = Py_Main(argc, argv_copy); for (i = 0; i < argc; i++) { PyMem_RawFree(argv_copy2[i]); } PyMem_RawFree(argv_copy); PyMem_RawFree(argv_copy2); return res; }
static int test_pre_initialization_api(void) { /* Leading "./" ensures getpath.c can still find the standard library */ wchar_t *program = Py_DecodeLocale("./spam", NULL); if (program == NULL) { fprintf(stderr, "Fatal error: cannot decode program name\n"); return 1; } Py_SetProgramName(program); Py_Initialize(); Py_Finalize(); PyMem_RawFree(program); return 0; }
static int test_pre_initialization_api(void) { /* Leading "./" ensures getpath.c can still find the standard library */ _Py_EMBED_PREINIT_CHECK("Checking Py_DecodeLocale\n"); wchar_t *program = Py_DecodeLocale("./spam", NULL); if (program == NULL) { fprintf(stderr, "Fatal error: cannot decode program name\n"); return 1; } _Py_EMBED_PREINIT_CHECK("Checking Py_SetProgramName\n"); Py_SetProgramName(program); _Py_EMBED_PREINIT_CHECK("Initializing interpreter\n"); Py_Initialize(); _Py_EMBED_PREINIT_CHECK("Check sys module contents\n"); PyRun_SimpleString("import sys; " "print('sys.executable:', sys.executable)"); _Py_EMBED_PREINIT_CHECK("Finalizing interpreter\n"); Py_Finalize(); _Py_EMBED_PREINIT_CHECK("Freeing memory allocated by Py_DecodeLocale\n"); PyMem_RawFree(program); return 0; }
CString CGenethonDoc::runTest4(PyObject* pModule, CString& function) { CString output = CString(); // CString fileName = "c:/users/karl/multiply.py"; /* CString fileName; GetTempFileName(fileName); fileName.Replace(".tmp", ".py"); CStdioFile wFile(fileName, CFile::modeWrite | CFile::typeText | CFile::modeCreate); wFile.WriteString("def multiply(a,b):\n"); wFile.WriteString(" print(\"Will compute\", a, \"times\", b)\n"); wFile.WriteString(" c = 0\n"); wFile.WriteString(" for i in range(0, a):\n"); wFile.WriteString(" c = c + b\n"); wFile.WriteString(" return c\n"); wFile.Close(); */ PyObject *pDict, *pFunc; PyObject *pArgs, *pValue; PyObject *ptype, *pvalue, *ptraceback; int i; numargs = 4; someString = CString("Very well done sir."); PyImport_AppendInittab("emb", &PyInit_emb); // Error checking of pName left out wchar_t *program = Py_DecodeLocale("GeneDoc", NULL); Py_SetProgramName(program); Py_Initialize(); if (pModule != NULL) { pFunc = PyObject_GetAttrString(pModule, function); // pFunc is a new reference if (pFunc && PyCallable_Check(pFunc)) { pArgs = PyTuple_New(2); pValue = PyLong_FromLong(2); if (!pValue) { Py_DECREF(pArgs); Py_DECREF(pModule); TRACE("Cannot convert argument\n"); return output; } PyTuple_SetItem(pArgs, 0, pValue); pValue = PyLong_FromLong(3); if (!pValue) { Py_DECREF(pArgs); Py_DECREF(pModule); TRACE("Cannot convert argument\n"); return output; } PyTuple_SetItem(pArgs, 1, pValue); // pValue reference stolen here: pValue = PyObject_CallObject(pFunc, pArgs); Py_DECREF(pArgs); if (pValue != NULL) { PyObject* v = PyObject_GetAttrString(pModule, "richTextOutput"); output.Format("Result of call: %ld\n%s", PyLong_AsLong(pValue), PyUnicode_AsUTF8(v)); Py_DECREF(pValue); TRACE(output); } else { Py_DECREF(pFunc); Py_DECREF(pModule); output = handlePyError(); TRACE(output); return output; } } else { if (PyErr_Occurred()) { output = handlePyError(); TRACE("Cannot find function \"%s\"\n", "multiply"); } } Py_XDECREF(pFunc); Py_DECREF(pModule); } else { PyErr_Print(); TRACE("pModule is null: Failed to load \n"); } return output; // DeleteTempFile(fileName); /* CString FileName; GetTempFileName(FileName); CStdioFile wFile(FileName, CFile::modeWrite | CFile::typeText | CFile::modeCreate); wFile.WriteString("Test test test test test test\n"); wFile.Close(); m_pTextView->LoadFile(FileName); DeleteTempFile(FileName); */ }
/* int main(int argc, char **argv) { */ int main(int argc, char *argv[]) { char *env_argument = NULL; char *env_entrypoint = NULL; char *env_logname = NULL; char entrypoint[ENTRYPOINT_MAXLEN]; int ret = 0; FILE *fd; setenv("P4A_BOOTSTRAP", "SDL2", 1); // env var to identify p4a to applications LOGP("Initializing Python for Android"); env_argument = getenv("ANDROID_ARGUMENT"); setenv("ANDROID_APP_PATH", env_argument, 1); env_entrypoint = getenv("ANDROID_ENTRYPOINT"); env_logname = getenv("PYTHON_NAME"); if (!getenv("ANDROID_UNPACK")) { /* ANDROID_UNPACK currently isn't set in services */ setenv("ANDROID_UNPACK", env_argument, 1); } if (env_logname == NULL) { env_logname = "python"; setenv("PYTHON_NAME", "python", 1); } LOGP("Changing directory to the one provided by ANDROID_ARGUMENT"); LOGP(env_argument); chdir(env_argument); Py_SetProgramName(L"android_python"); #if PY_MAJOR_VERSION >= 3 /* our logging module for android */ PyImport_AppendInittab("androidembed", initandroidembed); #endif LOGP("Preparing to initialize python"); // Set up the python path char paths[256]; char crystax_python_dir[256]; snprintf(crystax_python_dir, 256, "%s/crystax_python", getenv("ANDROID_UNPACK")); char python_bundle_dir[256]; snprintf(python_bundle_dir, 256, "%s/_python_bundle", getenv("ANDROID_UNPACK")); if (dir_exists(crystax_python_dir) || dir_exists(python_bundle_dir)) { if (dir_exists(crystax_python_dir)) { LOGP("crystax_python exists"); snprintf(paths, 256, "%s/stdlib.zip:%s/modules", crystax_python_dir, crystax_python_dir); } if (dir_exists(python_bundle_dir)) { LOGP("_python_bundle dir exists"); snprintf(paths, 256, "%s/stdlib.zip:%s/modules", python_bundle_dir, python_bundle_dir); } LOGP("calculated paths to be..."); LOGP(paths); #if PY_MAJOR_VERSION >= 3 wchar_t *wchar_paths = Py_DecodeLocale(paths, NULL); Py_SetPath(wchar_paths); #else char *wchar_paths = paths; LOGP("Can't Py_SetPath in python2, so crystax python2 doesn't work yet"); exit(1); #endif LOGP("set wchar paths..."); } else { // We do not expect to see crystax_python any more, so no point // reminding the user about it. If it does exist, we'll have // logged it earlier. LOGP("_python_bundle does not exist"); } Py_Initialize(); #if PY_MAJOR_VERSION < 3 PySys_SetArgv(argc, argv); #endif LOGP("Initialized python"); /* ensure threads will work. */ LOGP("AND: Init threads"); PyEval_InitThreads(); #if PY_MAJOR_VERSION < 3 initandroidembed(); #endif PyRun_SimpleString("import androidembed\nandroidembed.log('testing python " "print redirection')"); /* inject our bootstrap code to redirect python stdin/stdout * replace sys.path with our path */ PyRun_SimpleString("import sys, posix\n"); if (dir_exists("lib")) { /* If we built our own python, set up the paths correctly */ LOGP("Setting up python from ANDROID_PRIVATE"); PyRun_SimpleString("private = posix.environ['ANDROID_APP_PATH']\n" "argument = posix.environ['ANDROID_ARGUMENT']\n" "sys.path[:] = [ \n" " private + '/lib/python27.zip', \n" " private + '/lib/python2.7/', \n" " private + '/lib/python2.7/lib-dynload/', \n" " private + '/lib/python2.7/site-packages/', \n" " argument ]\n"); } char add_site_packages_dir[256]; if (dir_exists(crystax_python_dir)) { snprintf(add_site_packages_dir, 256, "sys.path.append('%s/site-packages')", crystax_python_dir); PyRun_SimpleString("import sys\n" "sys.argv = ['notaninterpreterreally']\n" "from os.path import realpath, join, dirname"); PyRun_SimpleString(add_site_packages_dir); /* "sys.path.append(join(dirname(realpath(__file__)), 'site-packages'))") */ PyRun_SimpleString("sys.path = ['.'] + sys.path"); } if (dir_exists(python_bundle_dir)) { snprintf(add_site_packages_dir, 256, "sys.path.append('%s/site-packages')", python_bundle_dir); PyRun_SimpleString("import sys\n" "sys.argv = ['notaninterpreterreally']\n" "from os.path import realpath, join, dirname"); PyRun_SimpleString(add_site_packages_dir); /* "sys.path.append(join(dirname(realpath(__file__)), 'site-packages'))") */ PyRun_SimpleString("sys.path = ['.'] + sys.path"); } PyRun_SimpleString( "class LogFile(object):\n" " def __init__(self):\n" " self.buffer = ''\n" " def write(self, s):\n" " s = self.buffer + s\n" " lines = s.split(\"\\n\")\n" " for l in lines[:-1]:\n" " androidembed.log(l)\n" " self.buffer = lines[-1]\n" " def flush(self):\n" " return\n" "sys.stdout = sys.stderr = LogFile()\n" "print('Android path', sys.path)\n" "import os\n" "print('os.environ is', os.environ)\n" "print('Android kivy bootstrap done. __name__ is', __name__)"); #if PY_MAJOR_VERSION < 3 PyRun_SimpleString("import site; print site.getsitepackages()\n"); #endif LOGP("AND: Ran string"); /* run it ! */ LOGP("Run user program, change dir and execute entrypoint"); /* Get the entrypoint, search the .pyo then .py */ char *dot = strrchr(env_entrypoint, '.'); if (dot <= 0) { LOGP("Invalid entrypoint, abort."); return -1; } if (strlen(env_entrypoint) > ENTRYPOINT_MAXLEN - 2) { LOGP("Entrypoint path is too long, try increasing ENTRYPOINT_MAXLEN."); return -1; } if (!strcmp(dot, ".pyo")) { if (!file_exists(env_entrypoint)) { /* fallback on .py */ strcpy(entrypoint, env_entrypoint); entrypoint[strlen(env_entrypoint) - 1] = '\0'; LOGP(entrypoint); if (!file_exists(entrypoint)) { LOGP("Entrypoint not found (.pyo, fallback on .py), abort"); return -1; } } else { strcpy(entrypoint, env_entrypoint); } } else if (!strcmp(dot, ".py")) { /* if .py is passed, check the pyo version first */ strcpy(entrypoint, env_entrypoint); entrypoint[strlen(env_entrypoint) + 1] = '\0'; entrypoint[strlen(env_entrypoint)] = 'o'; if (!file_exists(entrypoint)) { /* fallback on pure python version */ if (!file_exists(env_entrypoint)) { LOGP("Entrypoint not found (.py), abort."); return -1; } strcpy(entrypoint, env_entrypoint); } } else { LOGP("Entrypoint have an invalid extension (must be .py or .pyo), abort."); return -1; } // LOGP("Entrypoint is:"); // LOGP(entrypoint); fd = fopen(entrypoint, "r"); if (fd == NULL) { LOGP("Open the entrypoint failed"); LOGP(entrypoint); return -1; } /* run python ! */ ret = PyRun_SimpleFile(fd, entrypoint); if (PyErr_Occurred() != NULL) { ret = 1; PyErr_Print(); /* This exits with the right code if SystemExit. */ PyObject *f = PySys_GetObject("stdout"); if (PyFile_WriteString( "\n", f)) /* python2 used Py_FlushLine, but this no longer exists */ PyErr_Clear(); } /* close everything */ Py_Finalize(); fclose(fd); LOGP("Python for android ended."); return ret; }
/* int 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; LOGP("Initializing Python for Android"); // Set a couple of built-in environment vars: setenv("P4A_BOOTSTRAP", bootstrap_name, 1); // env var to identify p4a to applications env_argument = getenv("ANDROID_ARGUMENT"); setenv("ANDROID_APP_PATH", env_argument, 1); env_entrypoint = getenv("ANDROID_ENTRYPOINT"); env_logname = getenv("PYTHON_NAME"); if (!getenv("ANDROID_UNPACK")) { /* ANDROID_UNPACK currently isn't set in services */ setenv("ANDROID_UNPACK", env_argument, 1); } if (env_logname == NULL) { env_logname = "python"; setenv("PYTHON_NAME", "python", 1); } // Set additional file-provided environment vars: LOGP("Setting additional env vars from p4a_env_vars.txt"); char env_file_path[256]; snprintf(env_file_path, sizeof(env_file_path), "%s/p4a_env_vars.txt", getenv("ANDROID_UNPACK")); FILE *env_file_fd = fopen(env_file_path, "r"); if (env_file_fd) { char* line = NULL; size_t len = 0; while (getline(&line, &len, env_file_fd) != -1) { if (strlen(line) > 0) { char *eqsubstr = strstr(line, "="); if (eqsubstr) { size_t eq_pos = eqsubstr - line; // Extract name: char env_name[256]; strncpy(env_name, line, sizeof(env_name)); env_name[eq_pos] = '\0'; // Extract value (with line break removed: char env_value[256]; strncpy(env_value, (char*)(line + eq_pos + 1), sizeof(env_value)); if (strlen(env_value) > 0 && env_value[strlen(env_value)-1] == '\n') { env_value[strlen(env_value)-1] = '\0'; if (strlen(env_value) > 0 && env_value[strlen(env_value)-1] == '\r') { // Also remove windows line breaks (\r\n) env_value[strlen(env_value)-1] = '\0'; } } // Set value: setenv(env_name, env_value, 1); } } } fclose(env_file_fd); } else { LOGP("Warning: no p4a_env_vars.txt found / failed to open!"); } LOGP("Changing directory to the one provided by ANDROID_ARGUMENT"); LOGP(env_argument); chdir(env_argument); #if PY_MAJOR_VERSION < 3 Py_NoSiteFlag=1; #endif #if PY_MAJOR_VERSION < 3 Py_SetProgramName("android_python"); #else Py_SetProgramName(L"android_python"); #endif #if PY_MAJOR_VERSION >= 3 /* our logging module for android */ PyImport_AppendInittab("androidembed", initandroidembed); #endif LOGP("Preparing to initialize python"); // Set up the python path char paths[256]; char crystax_python_dir[256]; snprintf(crystax_python_dir, 256, "%s/crystax_python", getenv("ANDROID_UNPACK")); char python_bundle_dir[256]; snprintf(python_bundle_dir, 256, "%s/_python_bundle", getenv("ANDROID_UNPACK")); if (dir_exists(crystax_python_dir) || dir_exists(python_bundle_dir)) { if (dir_exists(crystax_python_dir)) { LOGP("crystax_python exists"); snprintf(paths, 256, "%s/stdlib.zip:%s/modules", crystax_python_dir, crystax_python_dir); } if (dir_exists(python_bundle_dir)) { LOGP("_python_bundle dir exists"); snprintf(paths, 256, "%s/stdlib.zip:%s/modules", python_bundle_dir, python_bundle_dir); } LOGP("calculated paths to be..."); LOGP(paths); #if PY_MAJOR_VERSION >= 3 wchar_t *wchar_paths = Py_DecodeLocale(paths, NULL); Py_SetPath(wchar_paths); #endif LOGP("set wchar paths..."); } else { // We do not expect to see crystax_python any more, so no point // reminding the user about it. If it does exist, we'll have // logged it earlier. LOGP("_python_bundle does not exist"); } Py_Initialize(); #if PY_MAJOR_VERSION < 3 // Can't Py_SetPath in python2 but we can set PySys_SetPath, which must // be applied after Py_Initialize rather than before like Py_SetPath #if PY_MICRO_VERSION >= 15 // Only for python native-build PySys_SetPath(paths); #endif 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. * This is only the case if we are using the python2legacy recipe */ LOGP("Setting up python from ANDROID_APP_PATH"); PyRun_SimpleString("private = posix.environ['ANDROID_APP_PATH']\n" "argument = posix.environ['ANDROID_ARGUMENT']\n" "sys.path[:] = [ \n" " private + '/lib/python27.zip', \n" " private + '/lib/python2.7/', \n" " private + '/lib/python2.7/lib-dynload/', \n" " private + '/lib/python2.7/site-packages/', \n" " argument ]\n"); } char add_site_packages_dir[256]; if (dir_exists(crystax_python_dir)) { snprintf(add_site_packages_dir, 256, "sys.path.append('%s/site-packages')", crystax_python_dir); PyRun_SimpleString("import sys\n" "sys.argv = ['notaninterpreterreally']\n" "from os.path import realpath, join, dirname"); PyRun_SimpleString(add_site_packages_dir); /* "sys.path.append(join(dirname(realpath(__file__)), 'site-packages'))") */ PyRun_SimpleString("sys.path = ['.'] + sys.path"); } if (dir_exists(python_bundle_dir)) { snprintf(add_site_packages_dir, 256, "sys.path.append('%s/site-packages')", python_bundle_dir); PyRun_SimpleString("import sys\n" "sys.argv = ['notaninterpreterreally']\n" "from os.path import realpath, join, dirname"); PyRun_SimpleString(add_site_packages_dir); /* "sys.path.append(join(dirname(realpath(__file__)), 'site-packages'))") */ PyRun_SimpleString("sys.path = ['.'] + sys.path"); } PyRun_SimpleString( "class LogFile(object):\n" " def __init__(self):\n" " self.buffer = ''\n" " def write(self, s):\n" " s = self.buffer + s\n" " lines = s.split(\"\\n\")\n" " for l in lines[:-1]:\n" " androidembed.log(l)\n" " self.buffer = lines[-1]\n" " def flush(self):\n" " return\n" "sys.stdout = sys.stderr = LogFile()\n" "print('Android path', sys.path)\n" "import os\n" "print('os.environ is', os.environ)\n" "print('Android kivy bootstrap done. __name__ is', __name__)"); #if PY_MAJOR_VERSION < 3 PyRun_SimpleString("import site; print site.getsitepackages()\n"); #endif LOGP("AND: Ran string"); /* run it ! */ LOGP("Run user program, change dir and execute entrypoint"); /* Get the entrypoint, search the .pyo then .py */ char *dot = strrchr(env_entrypoint, '.'); #if PY_MAJOR_VERSION > 2 char *ext = ".pyc"; #else char *ext = ".pyo"; #endif 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, ext)) { 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 (.pyc/.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'; #if PY_MAJOR_VERSION > 2 entrypoint[strlen(env_entrypoint)] = 'c'; #else entrypoint[strlen(env_entrypoint)] = 'o'; #endif 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 .pyc/.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); fclose(fd); 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(); } LOGP("Python for android ended."); /* Shut down: since regular shutdown causes issues sometimes (seems to be an incomplete shutdown breaking next launch) we'll use sys.exit(ret) to shutdown, since that one works. Reference discussion: https://github.com/kivy/kivy/pull/6107#issue-246120816 */ char terminatecmd[256]; snprintf( terminatecmd, sizeof(terminatecmd), "import sys; sys.exit(%d)\n", ret ); PyRun_SimpleString(terminatecmd); /* This should never actually be reached, but we'll leave the clean-up * here just to be safe. */ #if PY_MAJOR_VERSION < 3 Py_Finalize(); LOGP("Unexpectedly reached Py_FinalizeEx(), but was successful."); #else if (Py_FinalizeEx() != 0) // properly check success on Python 3 LOGP("Unexpectedly reached Py_FinalizeEx(), and got error!"); else LOGP("Unexpectedly reached Py_FinalizeEx(), but was successful."); #endif return ret; }
void embed_init_python(void) { FENTER; #ifndef PYTHON_SO_LIB #error "Python version needs passing in with -DPYTHON_SO_VERSION=libpython<ver>.so" #else #define PY_SO_LIB xstr(PYTHON_SO_LIB) #endif // Don't initialise python if already running if (gtstate) return; void * ret = utils_dyn_open(PY_SO_LIB); if (!ret) { fprintf(stderr, "Failed to find python lib\n"); } to_python(); // reset Program Name (i.e. argv[0]) if we are in a virtual environment char *venv_path_home = getenv("VIRTUAL_ENV"); if (venv_path_home) { char venv_path[strlen(venv_path_home)+64]; strcpy(venv_path, venv_path_home); strcat(venv_path, "/bin/python"); // this is universal in any VIRTUAL_ENV the python interpreter #if PY_MAJOR_VERSION >= 3 static wchar_t venv_path_w[1024]; #if PY_MINOR_VERSION >= 5 // Python3.5 + provides the locale decoder wcscpy(venv_path_w, Py_DecodeLocale(venv_path, NULL)); #else // for lesser python versions, we just hope the user specified his locales correctly setlocale (LC_ALL, ""); mbstowcs(venv_path_w, venv_path, sizeof(venv_path_w)); #endif LOG_INFO("Using virtualenv at %ls.", venv_path_w); Py_SetProgramName(venv_path_w); #else // Python2 case LOG_INFO("Using virtualenv at %s.", venv_path); Py_SetProgramName(venv_path); #endif } else { LOG_INFO("Did not detect virtual environment. Using system-wide Python interpreter."); } Py_Initialize(); /* Initialize the interpreter */ PySys_SetArgvEx(1, argv, 0); PyEval_InitThreads(); /* Create (and acquire) the interpreter lock */ /* Swap out and return current thread state and release the GIL */ gtstate = PyEval_SaveThread(); to_simulator(); /* Before returning we check if the user wants pause the simulator thread such that they can attach */ const char *pause = getenv("COCOTB_ATTACH"); if (pause) { long sleep_time = strtol(pause, NULL, 10); if (errno == ERANGE && (sleep_time == LONG_MAX || sleep_time == LONG_MIN)) { fprintf(stderr, "COCOTB_ATTACH only needs to be set to ~30 seconds"); goto out; } if ((errno != 0 && sleep_time == 0) || (sleep_time <= 0)) { fprintf(stderr, "COCOTB_ATTACH must be set to an integer base 10 or omitted"); goto out; } fprintf(stderr, "Waiting for %lu seconds - Attach to %d\n", sleep_time, getpid()); sleep(sleep_time); } out: FEXIT; }
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; }
/* int main(int argc, char **argv) { */ int main(int argc, char *argv[]) { char *env_argument = NULL; 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 */ LOG("Initialize Python for Android"); /* env_argument = "/data/data/org.kivy.android/files"; */ env_argument = getenv("ANDROID_ARGUMENT"); /* setenv("ANDROID_APP_PATH", env_argument, 1); */ /* setenv("ANDROID_ARGUMENT", env_argument, 1); */ /* setenv("ANDROID_PRIVATE", env_argument, 1); */ /* setenv("ANDROID_APP_PATH", env_argument, 1); */ /* setenv("PYTHONHOME", env_argument, 1); */ /* setenv("PYTHONPATH", "/data/data/org.kivy.android/files:/data/data/org.kivy.android/files/lib", 1); */ /* LOG("AND: Set env vars"); */ /* LOG(argv[0]); */ /* LOG("AND: That was argv 0"); */ //setenv("PYTHONVERBOSE", "2", 1); LOG("Changing directory to the one provided by ANDROID_ARGUMENT"); LOG(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 LOG("Preparing to initialize python"); if (dir_exists("crystax_python/")) { LOG("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); */ LOG("calculated paths to be..."); LOG(paths); #if PY_MAJOR_VERSION >= 3 wchar_t* wchar_paths = Py_DecodeLocale(paths, NULL); Py_SetPath(wchar_paths); #else char* wchar_paths = paths; LOG("Can't Py_SetPath in python2, so crystax python2 doesn't work yet"); exit(1); #endif LOG("set wchar paths..."); } else { LOG("crystax_python does not exist");} Py_Initialize(); #if PY_MAJOR_VERSION < 3 PySys_SetArgv(argc, argv); #endif LOG("Initialized python"); /* ensure threads will work. */ LOG("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 */ LOG("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__)"); /* PyRun_SimpleString( */ /* "import sys, posix\n" \ */ /* "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" \ */ /* "import androidembed\n" \ */ /* "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" \ */ /* "import site; print site.getsitepackages()\n"\ */ /* "print 'Android path', sys.path\n" \ */ /* "print 'Android kivy bootstrap done. __name__ is', __name__"); */ LOG("AND: Ran string"); /* run it ! */ LOG("Run user program, change dir and execute main.py"); /* search the initial main.py */ char *main_py = "main.pyo"; if ( file_exists(main_py) == 0 ) { if ( file_exists("main.py") ) main_py = "main.py"; else main_py = NULL; } if ( main_py == NULL ) { LOG("No main.pyo / main.py found."); return -1; } fd = fopen(main_py, "r"); if ( fd == NULL ) { LOG("Open the main.py(o) failed"); return -1; } /* run python ! */ ret = PyRun_SimpleFile(fd, main_py); 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); LOG("Python for android ended."); return ret; }
{"listmutator", listmutator, METH_VARARGS, "Return the number of arguments received by the process."}, {NULL, NULL, 0, NULL} }; PyModuleDef EmbModule = { PyModuleDef_HEAD_INIT, "emb", NULL, -1, EmbMethods, NULL, NULL, NULL, NULL }; PyObject* PyInit_emb(void) { return PyModule_Create(&EmbModule); } PyImport_AppendInittab("emb", &PyInit_emb); wchar_t *program = Py_DecodeLocale(argv[0], NULL); if (program == NULL) { fprintf(stderr, "Fatal error: cannot decode argv[0]\n"); exit(1); } Py_SetProgramName(program); /* optional but recommended */ Py_Initialize(); PyRun_SimpleString("from emb import listmutator\n" "a = [4, 5, 6, 7]\n" "listmutator(a)\n" "import pdb; pdb.set_trace()" ); Py_Finalize(); PyMem_RawFree(program); 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; }
static _PyInitError calculate_argv0_path(PyCalculatePath *calculate, const wchar_t *program_full_path) { wcsncpy(calculate->argv0_path, program_full_path, MAXPATHLEN); calculate->argv0_path[MAXPATHLEN] = '\0'; #ifdef WITH_NEXT_FRAMEWORK NSModule pythonModule; /* On Mac OS X we have a special case if we're running from a framework. ** This is because the python home should be set relative to the library, ** which is in the framework, not relative to the executable, which may ** be outside of the framework. Except when we're in the build directory... */ pythonModule = NSModuleForSymbol(NSLookupAndBindSymbol("_Py_Initialize")); /* Use dylib functions to find out where the framework was loaded from */ const char* modPath = NSLibraryNameForModule(pythonModule); if (modPath != NULL) { /* We're in a framework. */ /* See if we might be in the build directory. The framework in the ** build directory is incomplete, it only has the .dylib and a few ** needed symlinks, it doesn't have the Lib directories and such. ** If we're running with the framework from the build directory we must ** be running the interpreter in the build directory, so we use the ** build-directory-specific logic to find Lib and such. */ size_t len; wchar_t* wbuf = Py_DecodeLocale(modPath, &len); if (wbuf == NULL) { return DECODE_LOCALE_ERR("framework location", len); } wcsncpy(calculate->argv0_path, wbuf, MAXPATHLEN); reduce(calculate->argv0_path); joinpath(calculate->argv0_path, calculate->lib_python); joinpath(calculate->argv0_path, LANDMARK); if (!ismodule(calculate->argv0_path)) { /* We are in the build directory so use the name of the executable - we know that the absolute path is passed */ wcsncpy(calculate->argv0_path, program_full_path, MAXPATHLEN); } else { /* Use the location of the library as the program_full_path */ wcsncpy(calculate->argv0_path, wbuf, MAXPATHLEN); } PyMem_RawFree(wbuf); } #endif #if HAVE_READLINK wchar_t tmpbuffer[MAXPATHLEN+1]; int linklen = _Py_wreadlink(program_full_path, tmpbuffer, MAXPATHLEN); while (linklen != -1) { if (tmpbuffer[0] == SEP) { /* tmpbuffer should never be longer than MAXPATHLEN, but extra check does not hurt */ wcsncpy(calculate->argv0_path, tmpbuffer, MAXPATHLEN); } else { /* Interpret relative to program_full_path */ reduce(calculate->argv0_path); joinpath(calculate->argv0_path, tmpbuffer); } linklen = _Py_wreadlink(calculate->argv0_path, tmpbuffer, MAXPATHLEN); } #endif /* HAVE_READLINK */ reduce(calculate->argv0_path); /* At this point, argv0_path is guaranteed to be less than MAXPATHLEN bytes long. */ return _Py_INIT_OK(); }
static _PyInitError calculate_program_full_path(const _PyCoreConfig *core_config, PyCalculatePath *calculate, _PyPathConfig *config) { wchar_t program_full_path[MAXPATHLEN+1]; memset(program_full_path, 0, sizeof(program_full_path)); #ifdef __APPLE__ #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_4 uint32_t nsexeclength = MAXPATHLEN; #else unsigned long nsexeclength = MAXPATHLEN; #endif char execpath[MAXPATHLEN+1]; #endif /* If there is no slash in the argv0 path, then we have to * assume python is on the user's $PATH, since there's no * other way to find a directory to start the search from. If * $PATH isn't exported, you lose. */ if (wcschr(core_config->program_name, SEP)) { wcsncpy(program_full_path, core_config->program_name, MAXPATHLEN); } #ifdef __APPLE__ /* On Mac OS X, if a script uses an interpreter of the form * "#!/opt/python2.3/bin/python", the kernel only passes "python" * as argv[0], which falls through to the $PATH search below. * If /opt/python2.3/bin isn't in your path, or is near the end, * this algorithm may incorrectly find /usr/bin/python. To work * around this, we can use _NSGetExecutablePath to get a better * hint of what the intended interpreter was, although this * will fail if a relative path was used. but in that case, * absolutize() should help us out below */ else if(0 == _NSGetExecutablePath(execpath, &nsexeclength) && execpath[0] == SEP) { size_t len; wchar_t *path = Py_DecodeLocale(execpath, &len); if (path == NULL) { return DECODE_LOCALE_ERR("executable path", len); } wcsncpy(program_full_path, path, MAXPATHLEN); PyMem_RawFree(path); } #endif /* __APPLE__ */ else if (calculate->path_env) { wchar_t *path = calculate->path_env; while (1) { wchar_t *delim = wcschr(path, DELIM); if (delim) { size_t len = delim - path; if (len > MAXPATHLEN) { len = MAXPATHLEN; } wcsncpy(program_full_path, path, len); program_full_path[len] = '\0'; } else { wcsncpy(program_full_path, path, MAXPATHLEN); } joinpath(program_full_path, core_config->program_name); if (isxfile(program_full_path)) { break; } if (!delim) { program_full_path[0] = L'\0'; break; } path = delim + 1; } } else { program_full_path[0] = '\0'; } if (program_full_path[0] != SEP && program_full_path[0] != '\0') { absolutize(program_full_path); } config->program_full_path = _PyMem_RawWcsdup(program_full_path); if (config->program_full_path == NULL) { return _Py_INIT_NO_MEMORY(); } return _Py_INIT_OK(); }
/* search_for_prefix requires that argv0_path be no more than MAXPATHLEN bytes long. */ static int search_for_prefix(const _PyCoreConfig *core_config, PyCalculatePath *calculate, wchar_t *prefix) { size_t n; wchar_t *vpath; /* If PYTHONHOME is set, we believe it unconditionally */ if (core_config->home) { wcsncpy(prefix, core_config->home, MAXPATHLEN); prefix[MAXPATHLEN] = L'\0'; wchar_t *delim = wcschr(prefix, DELIM); if (delim) { *delim = L'\0'; } joinpath(prefix, calculate->lib_python); joinpath(prefix, LANDMARK); return 1; } /* Check to see if argv[0] is in the build directory */ wcsncpy(prefix, calculate->argv0_path, MAXPATHLEN); prefix[MAXPATHLEN] = L'\0'; joinpath(prefix, L"Modules/Setup.local"); if (isfile(prefix)) { /* Check VPATH to see if argv0_path is in the build directory. */ vpath = Py_DecodeLocale(VPATH, NULL); if (vpath != NULL) { wcsncpy(prefix, calculate->argv0_path, MAXPATHLEN); prefix[MAXPATHLEN] = L'\0'; joinpath(prefix, vpath); PyMem_RawFree(vpath); joinpath(prefix, L"Lib"); joinpath(prefix, LANDMARK); if (ismodule(prefix)) { return -1; } } } /* Search from argv0_path, until root is found */ copy_absolute(prefix, calculate->argv0_path, MAXPATHLEN+1); do { n = wcslen(prefix); joinpath(prefix, calculate->lib_python); joinpath(prefix, LANDMARK); if (ismodule(prefix)) { return 1; } prefix[n] = L'\0'; reduce(prefix); } while (prefix[0]); /* Look at configure's PREFIX */ wcsncpy(prefix, calculate->prefix, MAXPATHLEN); prefix[MAXPATHLEN] = L'\0'; joinpath(prefix, calculate->lib_python); joinpath(prefix, LANDMARK); if (ismodule(prefix)) { return 1; } /* Fail */ return 0; }