TestPythonEngineProperties.SetPythonPath avoids corrupting the module… · pythonnet/pythonnet@1f40564

@@ -181,13 +181,37 @@ public void SetProgramName()

181181

public void SetPythonPath()

182182

{

183183

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+185207

PythonEngine.Shutdown();

186208187209

PythonEngine.PythonPath = path;

188210

PythonEngine.Initialize();

189211190212

Assert.AreEqual(path, PythonEngine.PythonPath);

213+

if (importShouldSucceed) Py.Import(moduleName);

214+191215

PythonEngine.Shutdown();

192216

}

193217

}