我有一个关于通过C#以编程方式执行IronPython代码的问题。我使用IronPython 2.7.6.3。我的代码如下所示:
ScriptEngine scriptEngine = IPython.CreateEngine();
ScriptScope scriptScope = Engine.CreateScope();
scriptScope.ImportModule("clr");
scriptEngine.Execute("import clr", scriptScope);
scriptEngine.Execute("import System", scriptScope);
scriptEngine.Execute("clr.AddReference('System.Core')", scriptScope);
scriptEngine.Execute("clr.ImportExtensions(System.Linq)", scriptScope);
scriptEngine.Execute("from System import *", scriptScope);
ScriptSource scriptSource = scriptEngine.CreateScriptSourceFromString(string_with_ironpython_code);
scriptSource.Execute(scriptScope);
我的IronPython代码包含System.Linq命名空间中IEnumerable扩展方法的用法,这就是我使用System.Core和clr.ImportExtensions("")方法的原因。当我运行此代码时,我的Visual Studio挂起在这一行:
scriptSource.Execute(scriptScope);
我等了10分钟然后才停止了这个过程。但是,如果我删除添加对System.Core.dll的引用并导入扩展,那么我得到错误,我无法访问IEnumerable扩展方法。顺便说一句,当我执行另一个IronPython代码时,没有使用IEnumerable扩展方法,我不需要写这行:
scriptEngine.Execute("clr.AddReference('System.Core')", scriptScope);
scriptEngine.Execute("clr.ImportExtensions(System.Linq)", scriptScope);
万事如意。 所以我的问题是:我是否在添加引用和导入扩展时出错?或者当我尝试执行scriptSource并添加此引用时,为什么我的Visual Studio会挂起?
P.S。当我在Visual Studio中编写IronPython代码并从Visual Studio运行此* .py文件时 - 一切正常。