I have searched StackOverflow but didn't found a solution for my problem. I'm using Iron Python 2.7.3 DLR Hosting API. What i'm trying to do is invoke python functions of pure python script from C# code. I took example from here and this simple code is working as a charm. But my use case is little more complex and in my python module i'm doing imports of non standard packages and modules.
MyModule.py
import sys
sys.path.append(r"C:\Program Files (x86)\IronPython 2.7")
sys.path.append(r"C:\Program Files (x86)\IronPython 2.7\Lib")
sys.path.append(r"C:\Program Files (x86)\IronPython 2.7\Lib\lib2to3")
import os
import clr
sys.path.append(r'C:\MyPythonCodeLocation')
# mypackage are located at C:\MyPythonCodeLocation
import mypackage
def foo(p):
print '{0}: module - {1}, package - {2}'.format(p,__name__,__package__);
Then i calling foo function from c# like this
var pyRuntime = Python.CreateRuntime();
ScriptEngine pyEng = pyRuntime.GetEngine("python");
ScriptSource source = pyEng.CreateScriptSourceFromFile("MyModule.py");
ScriptScope scope = pyEng.CreateScope();
source.Execute(scope);
Func<int, bool> f = bis.GetVariable<Func<int, bool>>("foo");
f(1);
But Source.Execute(scope);
throws following exception - ValueError: Attempted relative import in non-package.
If i remove import mypackage
from the script everything is going fluently. Of course in python console this script is working fine and all imports resolved correctly.
One extra thing to mention, my Visual Studio project is located at C:\users\Me\MyDocuments......\PythonDLRTest and of course running from there. Importing packages located as shown at script and i'm guessing the problem that i'm facing is some how related to those paths.
May be someone can explain what i'm doing wrong and how this import problem can be resolved. Also it will be very interesting to understand a low level differences between python and ironpython and why the import resolution should be different.