I have a python library I am trying to use via IronPython (v2.7 RC1 [2.7.0.30]) invocation from C# application. The library uses NumPy and SciPy quite extensively, which does work with SciPy and NumPy for .NET when ran using ipy from command line like this:
ipy.exe -X:Frames file_from_lib_importing_numpy.py
However, when I invoke IronPython from C# using the code below, an exception is thrown:
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)
...
The C# code (a part of it) that invokes IronPython is as follows:
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"));
For testing purposes I am executing the following file '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
Which fails on the line 12 'import numpy as np'.
The problem is that the file __init__.py
in IronPython 2.7\Lib\site-packages\numpy\random\ contains the following line
from mtrand import *
which fails. Note that the mtrand is not a module, it is a directory. I can not think of anything else I can try to make this work, so I would very much appreciate any help from you. Thank you very much.
Not the best soultion, but its works for me:
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__
I hope it helps.