我们在开源项目中使用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));
现在导入代理触发了,但是在第一行崩溃,并出现“全局名称'mouse'未定义”的错误,该模块未使用mouse。当我将自定义全局变量添加到BuiltinModule时,似乎会产生混淆。