Problems implementing IronPython 2 in a C # web application

First background (if it helps):

My application is a web platform recently updated to version 3.5.NET Framework but not using Master Pages / User Controls. This is more like an MVC pattern (albeit a lot older) and outputs a clean HTML stream from the response stream from the patterns. Python expressions allow you to follow some rules and patterns.

Old way

When embedding the IronPython 1.x engine in C #, we were able to execute code, for example:

PythonEngine pe = new PythonEngine(); Assembly a = Assembly.LoadFile("path to assembly"); pe.LoadAssembly(a); pe.Import("Script"); 

There is no Import () method in ipy 2.0, and the ImportModule () method does not work the same. Import () made it easier to place a line in each python script we write, for example:

 from MyAssembly import MyClass 

The fact that MyClass is filled with static methods means that calls to MyClass.MyMethod () work very well. I can't just initialize the object and assign it to a variable in scope, because the assembly that contains MyClass is dynamically loaded at run time.

Now about the problem

I took apart all the other parts of IronPython 2.0 integration, but would prefer not to require my executors to enter "from MyAssembly import MyClass" at the top of every script they write (it just seems silly when it was not needed in ipy 1.x) and will probably be a support issue for a while.

And finally, the question

Has anyone had this problem and resolved it? Am I doing the wrong way for DLR? or am i missing something obvious?

I'm not sure of the details that anyone needs to help, but I hope this is enough.

+4
source share
2 answers

After loading the assembly, you can import into the Scope that you use to run the script:

 ScriptEngine engine = Python.CreateEngine(); engine.Runtime.LoadAssembly(a); string code = "from MyAssembly import MyClass"; ScriptSource source = engine.CreateScriptSourceFromString(code, "<import>", SourceCodeKind.Statements); CompiledCode c = source.Compile(); Scope scope = engine.CreateScope(); c.Execute(scope); // then run your script in the same scope 

We do something similar in our product.

(I hope this is really C # - I really tried this in IronPython because it was more convenient.)

+6
source

Thanks Wilberforce,

At the end, I did the following:

 Assembly a = Assembly.LoadFile("path to assembly"); object var = a.CreateInstance("MyNamespace.MyClass"); Scope.SetVariable("MyClass", var); 

This made an object of my class in C # and then passed it to the IronPython scope as a variable.

Note that this creates an object in the C # scope (AppDomain) and just passes it to IronPython. This seems to (for now) work for my problem, because the object I am passing is filled only with static methods, but may not work for a class with state.

+1
source

All Articles