|
| 1 | +// |
| 2 | +// PythonSupport.m |
| 3 | +// |
| 4 | +// Copyright (c) 2021 Changbeom Ahn |
| 5 | +// |
| 6 | +// Permission is hereby granted, free of charge, to any person obtaining a copy |
| 7 | +// of this software and associated documentation files (the "Software"), to deal |
| 8 | +// in the Software without restriction, including without limitation the rights |
| 9 | +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell |
| 10 | +// copies of the Software, and to permit persons to whom the Software is |
| 11 | +// furnished to do so, subject to the following conditions: |
| 12 | +// |
| 13 | +// The above copyright notice and this permission notice shall be included in |
| 14 | +// all copies or substantial portions of the Software. |
| 15 | +// |
| 16 | +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR |
| 17 | +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, |
| 18 | +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE |
| 19 | +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER |
| 20 | +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, |
| 21 | +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN |
| 22 | +// THE SOFTWARE. |
| 23 | +// |
| 24 | + |
| 25 | +#import <Python.h> |
| 26 | +#include <dlfcn.h> |
| 27 | + |
| 28 | +#import "PythonSupport.h" |
| 29 | + |
| 30 | +static void load_custom_builtin_importer(void); |
| 31 | + |
| 32 | +@implementation Python |
| 33 | + |
| 34 | +- (instancetype)initWithArgc:(int)argc argv:(const char *)argv |
| 35 | +{ |
| 36 | + self = [super init]; |
| 37 | + |
| 38 | + int ret = 0; |
| 39 | + |
| 40 | + // Special environment to prefer .pyo, and don't write bytecode if .py are found |
| 41 | + // because the process will not have a write attribute on the device. |
| 42 | + putenv("PYTHONOPTIMIZE=2"); |
| 43 | + putenv("PYTHONDONTWRITEBYTECODE=1"); |
| 44 | + putenv("PYTHONNOUSERSITE=1"); |
| 45 | + putenv("PYTHONPATH=."); |
| 46 | + putenv("PYTHONUNBUFFERED=1"); |
| 47 | + putenv("LC_CTYPE=UTF-8"); |
| 48 | + // putenv("PYTHONVERBOSE=1"); |
| 49 | + // putenv("PYOBJUS_DEBUG=1"); |
| 50 | + |
| 51 | + NSString * resourcePath = [[NSBundle bundleForClass:[Python class]] URLForResource:@"python3" withExtension:nil].path; |
| 52 | + NSString *python_home = [NSString stringWithFormat:@"PYTHONHOME=%@", resourcePath, nil]; |
| 53 | + putenv((char *)[python_home UTF8String]); |
| 54 | + |
| 55 | + NSString *python_path = [NSString stringWithFormat:@"PYTHONPATH=%@:%@/lib/python3.8/:%@/lib/python3.8/site-packages:.", resourcePath, resourcePath, resourcePath, nil]; |
| 56 | + putenv((char *)[python_path UTF8String]); |
| 57 | + |
| 58 | + NSString *tmp_path = [NSString stringWithFormat:@"TMP=%@/tmp", resourcePath, nil]; |
| 59 | + putenv((char *)[tmp_path UTF8String]); |
| 60 | + |
| 61 | + NSLog(@"Initializing python"); |
| 62 | + Py_Initialize(); |
| 63 | + |
| 64 | + wchar_t** python_argv = PyMem_RawMalloc(sizeof(wchar_t *) *argc); |
| 65 | + for (int i = 0; i < argc; i++) |
| 66 | + python_argv[i] = Py_DecodeLocale(argv[i], NULL); |
| 67 | + PySys_SetArgv(argc, python_argv); |
| 68 | + |
| 69 | + // If other modules are using the thread, we need to initialize them before. |
| 70 | + PyEval_InitThreads(); |
| 71 | + |
| 72 | + // Add an importer for builtin modules |
| 73 | + load_custom_builtin_importer(); |
| 74 | + |
| 75 | + return self; |
| 76 | +} |
| 77 | + |
| 78 | +- (instancetype)init |
| 79 | +{ |
| 80 | + return [self initWithArgc:0 argv:nil]; |
| 81 | +} |
| 82 | + |
| 83 | +- (void)dealloc |
| 84 | +{ |
| 85 | + Py_Finalize(); |
| 86 | + NSLog(@"Leaving"); |
| 87 | +} |
| 88 | + |
| 89 | +@end |
| 90 | + |
| 91 | +void load_custom_builtin_importer() { |
| 92 | + static const char *custom_builtin_importer = \ |
| 93 | + "import sys, imp, types\n" \ |
| 94 | + "from os import environ\n" \ |
| 95 | + "from os.path import exists, join\n" \ |
| 96 | + "try:\n" \ |
| 97 | + " # python 3\n" |
| 98 | + " import _imp\n" \ |
| 99 | + " EXTS = _imp.extension_suffixes()\n" \ |
| 100 | + " sys.modules['subprocess'] = types.ModuleType(name='subprocess')\n" \ |
| 101 | + " sys.modules['subprocess'].PIPE = None\n" \ |
| 102 | + " sys.modules['subprocess'].STDOUT = None\n" \ |
| 103 | + " sys.modules['subprocess'].DEVNULL = None\n" \ |
| 104 | + " sys.modules['subprocess'].CalledProcessError = Exception\n" \ |
| 105 | + " sys.modules['subprocess'].check_output = None\n" \ |
| 106 | + "except ImportError:\n" \ |
| 107 | + " EXTS = ['.so']\n" |
| 108 | + "# Fake redirection to supress console output\n" \ |
| 109 | + "if environ.get('KIVY_NO_CONSOLE', '0') == '1':\n" \ |
| 110 | + " class fakestd(object):\n" \ |
| 111 | + " def write(self, *args, **kw): pass\n" \ |
| 112 | + " def flush(self, *args, **kw): pass\n" \ |
| 113 | + " sys.stdout = fakestd()\n" \ |
| 114 | + " sys.stderr = fakestd()\n" \ |
| 115 | + "# Custom builtin importer for precompiled modules\n" \ |
| 116 | + "class CustomBuiltinImporter(object):\n" \ |
| 117 | + " def find_module(self, fullname, mpath=None):\n" \ |
| 118 | + " # print(f'find_module() fullname={fullname} mpath={mpath}')\n" \ |
| 119 | + " if '.' not in fullname:\n" \ |
| 120 | + " return\n" \ |
| 121 | + " if not mpath:\n" \ |
| 122 | + " return\n" \ |
| 123 | + " part = fullname.rsplit('.')[-1]\n" \ |
| 124 | + " for ext in EXTS:\n" \ |
| 125 | + " fn = join(list(mpath)[0], '{}{}'.format(part, ext))\n" \ |
| 126 | + " # print('find_module() {}'.format(fn))\n" \ |
| 127 | + " if exists(fn):\n" \ |
| 128 | + " return self\n" \ |
| 129 | + " return\n" \ |
| 130 | + " def load_module(self, fullname):\n" \ |
| 131 | + " f = fullname.replace('.', '_')\n" \ |
| 132 | + " mod = sys.modules.get(f)\n" \ |
| 133 | + " if mod is None:\n" \ |
| 134 | + " # print('LOAD DYNAMIC', f, sys.modules.keys())\n" \ |
| 135 | + " try:\n" \ |
| 136 | + " mod = imp.load_dynamic(f, f)\n" \ |
| 137 | + " except ImportError:\n" \ |
| 138 | + " # import traceback; traceback.print_exc();\n" \ |
| 139 | + " # print('LOAD DYNAMIC FALLBACK', fullname)\n" \ |
| 140 | + " mod = imp.load_dynamic(fullname, fullname)\n" \ |
| 141 | + " sys.modules[fullname] = mod\n" \ |
| 142 | + " return mod\n" \ |
| 143 | + " return mod\n" \ |
| 144 | + "sys.meta_path.insert(0, CustomBuiltinImporter())"; |
| 145 | + PyRun_SimpleString(custom_builtin_importer); |
| 146 | +} |
0 commit comments