我正在尝试将 python 2.6 嵌入到 .NET 4.0 中。
遵循“Python for .NET”中的极简文档,我编写了一个相当简单的代码,如下所示:
const string pythonModulePath = @"C:\Projects\PythonImport\PythonImport\test.py";
Environment.SetEnvironmentVariable("PYTHONHOME", Path.GetDirectoryName(python
ModulePath));
PythonEngine.Initialize();
var oldWorkingDirectory = Directory.GetCurrentDirectory();
var currWorkingDirectory = Path.GetDirectoryName(pythonModulePath);
Directory.SetCurrentDirectory(currWorkingDirectory);
var pyPlugin = PythonEngine.ImportModule(Path.GetFileNameWithoutExtension(python
ModulePath));
if (pyPlugin == null)
{
throw new PythonException();
}
Directory.SetCurrentDirectory(oldWorkingDirectory);
即使 test.py 是空的,我也会收到一个导入错误,说“没有名为警告的模块”。
'import site' failed; use -v for traceback
Unhandled Exception: Python.Runtime.PythonException: ImportError : No module nam
ed warnings
当您使用“python -v”(详细模式)运行 test.py 时,原因就很明显了。请注意,python 调用 #cleanup[2] 警告。
为什么 Python .NET 无法解决警告?该模块存在于 Lib 目录中。
有任何想法吗?