3

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 ?

3
  • "it doesn't work" - care to explain what happens? Commented Nov 29, 2011 at 7:57
  • related: stackoverflow.com/questions/4852386/… Commented Nov 29, 2011 at 7:58
  • @sehe rule.Execute<int>(scope); throws an exception like expected int but got null type or something similar. I can later update with the exact exception. If I just do rule.Execute(scope) the object returned is null. Commented Nov 29, 2011 at 8:03

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.