我有一个 python 库,我试图通过来自 C# 应用程序的 IronPython (v2.7 RC1 [2.7.0.30]) 调用来使用。该库非常广泛地使用 NumPy 和 SciPy,当从命令行使用 ipy 运行时,它确实可以与SciPy 和 NumPy for .NET一起使用,如下所示:
ipy.exe -X:Frames file_from_lib_importing_numpy.py
但是,当我使用以下代码从 C# 调用 IronPython 时,会引发异常:
ImportException
"No module named mtrand"
at Microsoft.Scripting.Runtime.LightExceptions.CheckAndThrow(Object value)
at IronPython.Runtime.Operations.PythonOps.ImportStar(CodeContext context, String fullName, Int32 level)
at Microsoft.Scripting.Interpreter.ActionCallInstruction3.Run(InterpretedFrame frame)
...
at Microsoft.Scripting.SourceUnit.Execute(Scope scope, ErrorSink errorSink)
at Microsoft.Scripting.Hosting.ScriptSource.Execute(ScriptScope scope)
at Microsoft.Scripting.Hosting.ScriptEngine.ExecuteFile(String path)
at Microsoft.Scripting.Hosting.ScriptRuntime.ExecuteFile(String path)
at Microsoft.Scripting.Hosting.ScriptRuntime.UseFile(String path)
...
调用 IronPython 的 C# 代码(其中的一部分)如下:
ScriptEngine _engine;
var opts = new Dictionary<string, object>();
opts["Frames"] = ScriptingRuntimeHelpers.True;
_engine = Python.CreateEngine(opts);
var sp = _engine.GetSearchPaths();
sp.Add(@"c:\Program Files\IronPython 2.7");
sp.Add(@"c:\Program Files\IronPython 2.7\DLLs");
sp.Add(@"c:\Program Files\IronPython 2.7\Lib");
sp.Add(@"c:\Program Files\IronPython 2.7\Lib\site-packages");
sp.Add(_path);
_engine.SetSearchPaths(sp);
var _runtime = _engine.Runtime;
var scope = _runtime.ExecuteFile(Path.Combine(_path, "mytest.py"));
出于测试目的,我正在执行以下文件“mytest.py”:
import sys
sys.path.append(r'c:\Program Files\IronPython 2.7')
sys.path.append(r'c:\Program Files\IronPython 2.7\DLLs')
sys.path.append(r'c:\Program Files\IronPython 2.7\Lib')
sys.path.append(r'c:\Program Files\IronPython 2.7\Lib\site-packages')
import os, os.path
cd = os.path.dirname(__file__)
if not cd in sys.path:
sys.path.append(os.path.dirname(__file__))
import numpy as np
print 'OK'
x = np.array([1,2])
print x
在第 12 行'import numpy as np'上失败了。问题是__init__.py
IronPython 2.7\Lib\site-packages\numpy\random\ 中的文件包含以下行
from mtrand import *
失败了。注意 mtrand 不是一个模块,它是一个目录。我想不出任何其他方法可以使这项工作,所以我非常感谢你的帮助。非常感谢。