Reputation: 11066
I am trying to call an IronPython (2.7.1) script from C# (4.0)
This is related to IronPython integration in C#: a specific problem/question
I have a python script like below in a file script.py
import clr
def getStream(activity):
if activity.ActivityType == 'XXX':
if activity.Complexity == 'LOW':
return 1
else:
return 2
else:
return 0
getStream(activity)
I am trying to pre-compile the script and reuse it later
ScriptEngine engine = Python.CreateEngine();
ScriptSource source = engine.CreateScriptSourceFromFile("script.py");
CompiledCode compiledCode = source.Compile();
dynamic scope = engine.CreateScope();
// .. creating an activity object here
scope.SetVariable("activity", activity);
Now to get the streamId if I do this it doesn't work
int streamId = rule.Execute<int>(scope);
The exception is
IronPython.Runtime.Exceptions.TypeErrorException was unhandled by user code
Message=expected int, got NoneType
But this will work
rule.Execute(scope);
int streamId = scope.getWorkstream(activity);
My question is what is the correct usage of calling Execute method of the CompiledCode class ?
Upvotes: 3
Views: 1447
Reputation: 7662
I believe Execute
will only return a value if the compiled code is an expression, not a series of statements. Your second usage is the correct one in this case.
If the code was simply '2 + 2' then Execute<int>
would probably work, but I'm unable to check that at the moment.
Upvotes: 2