我以前使用过这种方法,既可以将IronPython脚本保存在数据库中,也可以保存在文件中。我喜欢的模式是用约定的名称存储Python函数。换句话说,如果您正在处理Foo类型的对象,那么在.py文件或表中可能有一个名为“Foo\u filter”的Python函数。最终,您可以执行一个Python文件并将函数解析到函数引用的字典中。
你的foo课程:
public class Foo {
public string Bar { get; set; }
}
设置Foo并调用getPythonFunc(i);
var items = new List<Foo>() {
new Foo() { Bar = "connecticut" },
new Foo() { Bar = "new york" },
new Foo() { Bar = "new jersey" }
};
items.ForEach((i) => { getPythonFunc(i); Console.WriteLine(i.Bar); });
一个快速而肮脏的getPythonFun实现。。。显然,ScriptXXX对象图应该被缓存,GetVariable()检索到的变量也应该被缓存。
static void getPythonFunc(Foo foo) {
ScriptRuntimeSetup setup = ScriptRuntimeSetup.ReadConfiguration();
ScriptRuntime runtime = new ScriptRuntime(setup);
runtime.LoadAssembly(Assembly.GetExecutingAssembly());
ScriptEngine engine = runtime.GetEngine("IronPython");
ScriptScope scope = engine.CreateScope();
engine.ExecuteFile("filter.py", scope);
var filterFunc = scope.GetVariable("filter_item");
scope.Engine.Operations.Invoke(filterFunc, foo);
}
内容filter.py:
def filter_item(item):
item.Bar = item.Bar.title()
基于属性应用规则的简单方法(不是在Foo上添加Size属性):
var items = new List<Foo>() {
new Foo() { Bar = "connecticut", Size = "Small" },
new Foo() { Bar = "new york", Size = "Large" },
new Foo() { Bar = "new jersey", Size = "Medium" }
};
更改getPythonFun()中调用ScriptScope的GetVariable()的行:
var filterFunc = scope.GetVariable("filter_" + foo.Size.ToLower());
以及filter.py
def filter_small(item):
item.Bar = item.Bar.lower()
def filter_medium(item):
item.Bar = item.Bar.title()
def filter_large(item):
item.Bar = item.Bar.upper()
我有一堆更完整的样品可以在
http://www.codevoyeur.com/Articles/Tags/ironpython.aspx