gpt4 book ai didi

c# - 从模块访问脚本范围变量

转载 作者:行者123 更新时间:2023-11-28 18:37:21 25 4
gpt4 key购买 nike

我们在我们的开源项目中使用 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;
}

https://github.com/AndersMalmgren/FreePIE/blob/master/FreePIE.Core/ScriptEngine/Python/PythonScriptEngine.cs#L267

我可以使用主脚本中的全局变量,但加载的任何模块都会失败。如何修复?

更新:鉴于此模块 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));
});
}

https://github.com/AndersMalmgren/FreePIE/blob/master/FreePIE.Core/ScriptEngine/Python/PythonScriptEngine.cs#L163

from mymodule import * #this will load the moduel and it fails with

enter image description here

编辑:回应@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));

现在导入委托(delegate)触发,但它在第一行崩溃,global name 'mouse' is not defined,模块未使用鼠标。当我将自定义全局变量添加到 BuiltinModule

时,它似乎很困惑

最佳答案

这可能不是正确的答案,因为仍然不允许与导入的模块共享主 IronPhyton 脚本中定义的变量,但这是向前迈出的一步。

这种方法允许在引擎级别而不是脚本级别设置变量,并且它们将在每个导入的模块中可用。

engine = Python.CreateEngine();
engine.Runtime.Globals.SetVariable("test_global", "This is a test global variable.");

然后,在任何 IronPhyton 脚本中都可以使用导入访问它:

import test_global
print(test_global)

与使它们直接可用的 ScriptScope 不同,这些全局变量需要导入。

原创文章
https://ludovic.chabant.com/devblog/2009/12/24/exposing-global-variables-in-ironpython/

免责声明
我添加了这个答案,因为除了这个 SO 问答之外,我一直在努力寻找关于这个主题的任何 Material ,所以我发布了这个可能的解决方法来帮助 future 遇到麻烦的读者(比如我自己)

关于c# - 从模块访问脚本范围变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31245060/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com