这是可能的。您只需要像这样将搜索路径添加到 ScriptEngine 对象:
var paths = engine.GetSearchPaths();
paths.Add(yourLibsPath); // add directory to search
或
engine.SetSearchPaths(paths);
然后你可以使用你添加的目录中的任何模块:
import pyFileName # without extension .py
更新
好的。如果你想使用像模块这样的嵌入式资源字符串,你可以使用这个代码:
var scope = engine.CreateScope(); // Create ScriptScope to use it like a module
engine.Execute("import clr\n" +
"clr.AddReference(\"System.Windows.Forms\")\n" +
"import System.Windows.Forms\n" +
"def Hello():\n" +
"\tSystem.Windows.Forms.MessageBox.Show(\"Hello World!\")", scope); // Execute code from string in scope.
现在您有了一个包含所有已执行函数的 ScriptScope 对象(代码中的 scope)。你可以像这样将它们插入到另一个作用域中:
foreach (var keyValuePair in scope.GetItems())
{
if(keyValuePair.Value != null)
anotherScope.SetVariable(keyValuePair.Key, keyValuePair.Value);
}
或者你可以直接在这个 ScriptScope 中执行你的脚本:
dynamic executed = engine.ExecuteFile("Filename.py", scope);
executed.SomeFuncInFilename();
在这个脚本中你可以使用所有没有import的函数:
def SomeFuncInFilename():
Hello() # uses function from your scope