【发布时间】:2020-07-23 14:05:44
【问题描述】:
我们在开源项目中使用 IronPython。我在访问添加到脚本范围的变量时遇到问题,例如
private ScriptScope CreateScope(IDictionary<string, object> globals)
{
globals.Add("starting", true);
globals.Add("stopping", false);
var scope = Engine.CreateScope(globals);
scope.ImportModule("math");
return scope;
}
我可以使用主脚本中的全局变量,但任何加载的模块都会失败。怎么解决?
更新:给定这个模块 mymodule.py
if starting: #starting is defined on the scope
...
来自使用此代码执行的主脚本
void RunLoop(string script, ScriptScope scope)
{
ExecuteSafe(() =>
{
var compiled = Engine.CreateScriptSourceFromString(script).Compile();
while (!stopRequested)
{
usedPlugins.ForEach(p => p.DoBeforeNextExecute());
CatchThreadAbortedException(() => compiled.Execute(scope));
scope.SetVariable("starting", false);
threadTimingFactory.Get().Wait();
}
scope.SetVariable("stopping", true);
CatchThreadAbortedException(() => compiled.Execute(scope));
});
}
from mymodule import * #this will load the moduel and it fails with
编辑:回应@BendEg 的回答
我试过了
scope.SetVariable("__import__", new Func<CodeContext, string, PythonDictionary, PythonDictionary, PythonTuple, object>(ResolveImport));
ImportDelegate 未定义,因此尝试使用 Func 代替,ResolveImport 方法永远不会触发,我得到与未定义名称相同的异常
编辑:我将范围创建更改为
var scope = Engine.GetBuiltinModule();
globals.ForEach(g => scope.SetVariable(g.Key, g.Value));
现在导入委托触发,但它在第一行与global name 'mouse' is not defined 崩溃,模块未使用鼠标。当我将自定义全局变量添加到 BuiltinModule
【问题讨论】:
-
您能否提供一个更完整的示例(例如,针对该范围执行了什么以及它如何失败)?
标签: c# python ironpython