IronPython和C# - 脚本访问C#对象

Gab*_*erg 4 c# ironpython

请考虑以下代码:

ScriptRuntimeSetup setup = Python.CreateRuntimeSetup(null);
ScriptRuntime runtime = new ScriptRuntime(setup);
ScriptEngine engine = Python.GetEngine(runtime);
ScriptScope scope = engine.CreateScope();

scope.SetVariable("message", "Hello, world!");
string script = @"print message";
ScriptSource source = scope.Engine.CreateScriptSourceFromString(script, SourceCodeKind.Statements);
source.Execute();
Run Code Online (Sandbox Code Playgroud)

此代码产生以下异常:

Microsoft.Scripting.Runtime.UnboundNameException未处理Message ="name'message'未定义"

我错过了什么?

小智 7

它应该是"source.Execute(scope);" 而不是"source.Execute();"