| 118 | } |
| 119 | |
| 120 | void mitk::PythonContext::Activate(bool importBindings) |
| 121 | { |
| 122 | std::ostringstream pyCommands; pyCommands |
| 123 | << "import os, site, sys\n" |
| 124 | << "def add_site_packages(base_path):\n" |
| 125 | << " if os.name == 'nt':\n" |
| 126 | << " site_packages = os.path.join(base_path, 'Lib', 'site-packages')\n" |
| 127 | << " else:\n" |
| 128 | << " version = f'python{sys.version_info.major}.{sys.version_info.minor}'\n" |
| 129 | << " site_packages = os.path.join(base_path, 'lib', version, 'site-packages')\n" |
| 130 | << " if site_packages not in sys.path:\n" |
| 131 | << " site.addsitedir(site_packages)\n" |
| 132 | << "add_site_packages(sys.base_prefix)\n"; |
| 133 | |
| 134 | // Importing NumPy (and the MITK module, which pulls it in) maps the venv's |
| 135 | // compiled extensions on Linux, where the venv is sys.prefix. Skip it for |
| 136 | // metadata-only contexts so an "is any venv module loaded?" check stays |
| 137 | // honest. See Activate()'s documentation. |
| 138 | if (importBindings) |
| 139 | { |
| 140 | std::string appPath = IOUtil::GetAppBundlePath(IOUtil::AppBundlePath::Parent).string(); |
| 141 | |
| 142 | #if defined(_WIN32) |
| 143 | std::replace(appPath.begin(), appPath.end(), '\\', '/'); |
| 144 | #endif |
| 145 | |
| 146 | pyCommands |
| 147 | << "import numpy as np\n" |
| 148 | << "app_dir = '" << appPath << "'\n" |
| 149 | << "if app_dir not in sys.path:\n" |
| 150 | << " sys.path.insert(0, app_dir)\n" |
| 151 | << "import mitk\n"; |
| 152 | } |
| 153 | |
| 154 | pyCommands |
| 155 | << "venv = os.environ.get('VIRTUAL_ENV')\n" |
| 156 | << "if venv:\n" |
| 157 | << " add_site_packages(venv)\n"; |
| 158 | |
| 159 | this->Execute(pyCommands.str()); |
| 160 | } |
| 161 | |
| 162 | mitk::PythonContext::~PythonContext() |
| 163 | { |