python_main.cxx 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. /**
  2. * PANDA 3D SOFTWARE
  3. * Copyright (c) Carnegie Mellon University. All rights reserved.
  4. *
  5. * All use of this software is subject to the terms of the revised BSD
  6. * license. You should have received a copy of this license along
  7. * with this source code in a file named "LICENSE."
  8. *
  9. * @file python_main.cxx
  10. * @author rdb
  11. * @date 2018-02-12
  12. */
  13. #include "dtoolbase.h"
  14. #include "config_android.h"
  15. #include "executionEnvironment.h"
  16. #undef _POSIX_C_SOURCE
  17. #undef _XOPEN_SOURCE
  18. #include <Python.h>
  19. #if PY_MAJOR_VERSION >= 3
  20. #include <wchar.h>
  21. #endif
  22. #include <dlfcn.h>
  23. /**
  24. * The main entry point for the Python activity. Called by android_main.
  25. */
  26. int main(int argc, char *argv[]) {
  27. if (argc <= 1) {
  28. return 1;
  29. }
  30. // Help out Python by telling it which encoding to use
  31. Py_FileSystemDefaultEncoding = "utf-8";
  32. Py_SetProgramName(Py_DecodeLocale("ppython", nullptr));
  33. // Set PYTHONHOME to the location of the .apk file.
  34. string apk_path = ExecutionEnvironment::get_binary_name();
  35. Py_SetPythonHome(Py_DecodeLocale(apk_path.c_str(), nullptr));
  36. // We need to make zlib available to zipimport, but I don't know how
  37. // we could inject our import hook before Py_Initialize, so instead
  38. // load it as though it were a built-in module.
  39. void *zlib = dlopen("libpy.zlib.so", RTLD_NOW);
  40. if (zlib != nullptr) {
  41. void *init = dlsym(zlib, "PyInit_zlib");
  42. if (init != nullptr) {
  43. PyImport_AppendInittab("zlib", (PyObject *(*)())init);
  44. }
  45. }
  46. Py_Initialize();
  47. // This is used by the import hook to locate the module libraries.
  48. Filename dtool_name = ExecutionEnvironment::get_dtool_name();
  49. string native_dir = dtool_name.get_dirname();
  50. PyObject *py_native_dir = PyUnicode_FromStringAndSize(native_dir.c_str(), native_dir.size());
  51. PySys_SetObject("_native_library_dir", py_native_dir);
  52. Py_DECREF(py_native_dir);
  53. int sts = 1;
  54. FILE *fp = fopen(argv[1], "r");
  55. if (fp != nullptr) {
  56. int res = PyRun_AnyFile(fp, argv[1]);
  57. if (res > 0) {
  58. sts = 0;
  59. } else {
  60. android_cat.error() << "Error running " << argv[1] << "\n";
  61. PyErr_Print();
  62. }
  63. } else {
  64. android_cat.error() << "Unable to open " << argv[1] << "\n";
  65. }
  66. Py_Finalize();
  67. return sts;
  68. }