我正在努力解决用户界面,用户可以输入底层数据的简单表达式,以使用IronPython获得一些自定义输出。
我做了什么...
using System;
using IronPython.Hosting;
namespace SimpleTest
{
class Program
{
static void Main(string[] args)
{
var engine = Python.CreateEngine();
var scope = engine.CreateScope();
scope.SetVariable("a", new Person("A", 18));
scope.SetVariable("b", new Person("B", 24));
object result = null;
try
{
//result = engine.Execute<object>("a.Age + b.Age", scope);
result = engine.Execute<object>("a.Age + b.Grade", scope);
}
catch (Exception e)
{
// Error Message : 'Person' object has no attribute 'Grade'
// TODO HOW TO GET Character Span Location?
Console.WriteLine(e);
}
Console.WriteLine("Result:{0}", result);
}
}
public class Person
{
public string Name { get; private set; }
public double Age { get; private set; }
public Person(string name, double age)
{
Name = name;
Age = age;
}
}
}
如您所见,传入engine.Execute<object>
表达式无效,因为类中没有Grade
prop,因此引擎按预期抛出异常,但它不包含有关文本字符位置的任何信息,这些信息很好以红色等出色颜色向用户显示。
有什么提示吗?
我用谷歌搜索但没有找到任何答案。我发现的唯一内容是在文件名信息中显示行号。
谢谢
可以检查异常的 Data
属性以获取行信息。 Data
属性包含一个字典,该字典由表示要检查的对象的类型对象键入。
您需要从数据中获取InterpretedFrameInfo
。它作为InterpretedFrameInfo
对象的集合给出。 它们本质上是脚本失败时的堆栈跟踪。 DebugInfo
将包含所需的信息。 您还可以检查DynamicStackFrame
以检查帧的实际内容。 您可以作为IReadOnlyList
访问每个集合。
if (e.Data[typeof(Microsoft.Scripting.Interpreter.InterpretedFrameInfo)]
is IReadOnlyList<Microsoft.Scripting.Interpreter.InterpretedFrameInfo> trace)
{
// do stuff with trace
}
if (e.Data[typeof(Microsoft.Scripting.Runtime.DynamicStackFrame)]
is IReadOnlyList<Microsoft.Scripting.Runtime.DynamicStackFrame> frames)
{
// do stuff with frames
}
请记住,脚本中似乎注入了一些引导代码,因此帧中的Index
可能已关闭。 就我而言,我看到简单表达式的偏移量为 23
。