| FazBrowse GitHub Viewer | Trending | | Home |
| Tools: [Download Repo ZIP] [Original HTTPS Page] |
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
@@ -181,13 +181,37 @@ public void SetProgramName() | |||
| 181 | 181 | public void SetPythonPath() | |
| 182 | 182 | { | |
| 183 | 183 | PythonEngine.Initialize(); | |
| 184 | - string path = PythonEngine.PythonPath; | ||
| 184 | + | ||
| 185 | + const string moduleName = "pytest"; | ||
| 186 | + bool importShouldSucceed; | ||
| 187 | + try | ||
| 188 | + { | ||
| 189 | + Py.Import(moduleName); | ||
| 190 | + importShouldSucceed = true; | ||
| 191 | + } | ||
| 192 | + catch | ||
| 193 | + { | ||
| 194 | + importShouldSucceed = false; | ||
| 195 | + } | ||
| 196 | + | ||
| 197 | + string[] paths = Py.Import("sys").GetAttr("path").As<string[]>(); | ||
| 198 | + string path = string.Join(System.IO.Path.PathSeparator.ToString(), paths); | ||
| 199 | + | ||
| 200 | + // path should not be set to PythonEngine.PythonPath here. | ||
| 201 | + // PythonEngine.PythonPath gets the default module search path, not the full search path. | ||
| 202 | + // The list sys.path is initialized with this value on interpreter startup; | ||
| 203 | + // it can be (and usually is) modified later to change the search path for loading modules. | ||
| 204 | + // See https://docs.python.org/3/c-api/init.html#c.Py_GetPath | ||
| 205 | + // After PythonPath is set, then PythonEngine.PythonPath will correctly return the full search path. | ||
| 206 | + | ||
| 185 | 207 | PythonEngine.Shutdown(); | |
| 186 | 208 | ||
| 187 | 209 | PythonEngine.PythonPath = path; | |
| 188 | 210 | PythonEngine.Initialize(); | |
| 189 | 211 | ||
| 190 | 212 | Assert.AreEqual(path, PythonEngine.PythonPath); | |
| 213 | + if (importShouldSucceed) Py.Import(moduleName); | ||
| 214 | + | ||
| 191 | 215 | PythonEngine.Shutdown(); | |
| 192 | 216 | } | |
| 193 | 217 | } | |
| Back | FazBrowse Home | New Git URL |
0 commit comments