来自C#(使用SciPy)的IronPython调用因ImportException失败:“没有名为mtrand的模块”

我有一个python库,我试图通过IronPython(v2.7 RC1 [2.7.0.30])从C#应用程序调用。 该库非常广泛地使用NumPy和SciPy,当从命令行使用ipy运行时,它可以与SciPy和NumPy for .NET一起使用,如下所示:

ipy.exe -X:Frames file_from_lib_importing_numpy.py 

但是,当我使用下面的代码从C#调用IronPython时,会抛出exception:

 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(); 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行导入numpy失败为np’。 问题是IronPython 2.7 \ Lib \ site-packages \ numpy \ random \中的文件__init__.py包含以下行

 from mtrand import * 

哪个失败了。 请注意,mtrand不是模块,而是目录 。 我想不出别的什么我可以尝试使这项工作,所以我非常感谢你的任何帮助。 非常感谢你。

不是最好的灵魂,但它对我有用:

 import sys sys.path.append(r'c:\Program Files (x86)\IronPython 2.7') sys.path.append(r'c:\Program Files (x86)\IronPython 2.7\DLLs') sys.path.append(r'c:\Program Files (x86)\IronPython 2.7\Lib') sys.path.append(r'c:\Program Files (x86)\IronPython 2.7\Lib\site-packages') import clr clr.AddReference('mtrand.dll') import numpy import scipy print numpy.__version__ print scipy.__version__ 

我希望它有所帮助。

我发现,在我的ActivePython V2.7.0.2中,这有效:

 sys.path.append(r'C:\\Examples') import examples 

(假设examples.py在C:\ Examples中)。 这不(没有r):

 sys.path.append('C:\\Examples') import examples 

因为我得到了这个:

 Traceback (most recent call last): File "", line 1, in  ImportError: No module named examples 

结论:记住r”!