c# - 有没有办法将嵌入式 python 脚本作为 python 模块导入到 IronPython 中?

标签 c# python ironpython

我的 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

更新 好的。如果您想使用模块等嵌入资源字符串,您可以使用以下代码:

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 对象(代码中的范围),其中包含所有已执行的函数。您可以将它们插入到另一个作用域中,如下所示:

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

关于c# - 有没有办法将嵌入式 python 脚本作为 python 模块导入到 IronPython 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18568682/

相关文章:

python - coverage.py 不适用于相对导入?

python - Ascii 字符 27 (ESC) 导致 Python 错误

c# - IronPython 在线程中使用 numpy 时抛出 InsufficientMemoryException

python - 可以在 ironpython 2.7.5 中使用请求吗?

Python 多处理性能

Python:AttributeError: 'module' 对象没有属性 'AddReference'?

c# - MS Word 2010 无法打开宏存储

c# - 使用变量的值设置面板的可见性

c# - 根据文件填充一组复选框

c# - Threading.Timer阻止GC收集