IronPython在C#中的集成:一个特定的问题/问题

Igo*_*ejc 4 c# ironpython

我正在通过IronPython为我的C#mapmaking应用程序提供可扩展性机制.一切正常,但我有一个特定的要求,我无法实现:我希望用户能够指定两件事:

  1. 要加载的Python脚本的文件名
  2. 包含Python脚本的单行字符串,通常是从该Python文件调用函数(示例getTextLabel(element))

这两个设置必须是分开的,但我不知道是否可以使用PythonScript相关类来完成此操作.

我是Python的新手,或许有另一种方法可以实现这一目标?出于性能原因,我想避免多次加载和编译Python脚本文件(因为可能存在上面提到的几个不同的"函数调用"设置,CompiledCode如果可能的话我想重用该文件的实例).

更新:@digEmAll给出了我的问题的正确答案,所以我接受它作为一个有效的答案.但如果你关心表现,你也应该看看我自己的答案.

dig*_*All 5

你可以这样做:

string importScript = "import sys" + Environment.NewLine +
                      "sys.path.append( r\"{0}\" )" + Environment.NewLine +
                      "from {1} import *";

// python script to load
string fullPath = @"c:\path\mymodule.py";

var engine = Python.CreateEngine();
ScriptScope scope = engine.CreateScope();

// import the module
string scriptStr = string.Format(importScript,
                                 Path.GetDirectoryName(fullPath),
                                 Path.GetFileNameWithoutExtension(fullPath));
var importSrc = engine.CreateScriptSourceFromString(scriptStr,Microsoft.Scripting.SourceCodeKind.File);
importSrc.Execute(scope);

// now you ca execute one-line expressions on the scope e.g.
string expr = "functionOfMyModule()";
var result = engine.Execute(expr, scope);
Run Code Online (Sandbox Code Playgroud)

只要保留scope模块的加载位置,就可以调用模块的功能而无需重新加载.