有没有一种方法可以将嵌入式python脚本作为python模块导入IronPython
本文关键字:python 脚本 嵌入式 IronPython 导入 模块 一种 方法 有没有 | 更新日期: 2023-09-27 18:29:56
我的dll中有一个嵌入的资源,它是一个python脚本。我想让python引擎可以使用该资源中的类和函数,这样我就可以执行外部.py文件(作为__main__
),它可以执行类似的操作
import embedded_lib # where embedded_lib is an embedded python script
有办法做到这一点吗?我希望会有某种IronPython.ImportModule('module_name', source)
,所以我看了IronPython的文档,什么都找不到,但我希望我只是不擅长看。。也许有某种方法可以拦截对import
的调用并以这种方式加载我的脚本?
这是可能的。您只需要向ScriptEngine对象添加搜索路径,如下所示:
var paths = engine.GetSearchPaths();
paths.Add(yourLibsPath); // add directory to search
或
engine.SetSearchPaths(paths);
然后你可以使用目录中的任何模块,你可以添加:
import pyFileName # without extension .py
更新好的。如果你想使用像module这样的嵌入式资源字符串,你可以使用以下代码:
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();
在这个脚本中,您可以使用所有没有导入的函数:
def SomeFuncInFilename():
Hello() # uses function from your scope