我正在尝试将 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 为空,我也会收到一个导入错误,提示“No module named warnings”。
'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 目录中。
有什么想法吗?
最佳答案
我认为默认情况下 Python 引擎不会自动设置您需要的路径。
http://www.voidspace.org.uk/ironpython/custom_executable.shtml有一个嵌入 ironpython 的例子。看起来你错过了类似的东西
PythonEngine engine = new PythonEngine();
engine.AddToPath(Path.GetDirectoryName(Application.ExecutablePath));
engine.AddToPath(MyPathToStdLib);
除非我知道在哪里以及是否安装了 Ironpython,否则我更愿意找到我需要的所有标准模块,将它们编译成 IPyStdLibDLL,然后根据我的代码执行以下操作
import clr
clr.addReference("IPyStdLib")
import site
关于.NET 的 Python : ImportError: No module named warnings,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4712665/