我正在努力使用UI,用户可以使用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
道具,因此引擎会按预期抛出异常,但它不包含有关字符位置的任何信息用红色等优秀的颜色向用户展示的文本。
有任何提示吗?
我用谷歌搜索但没有找到任何答案。只有我发现的是在文件名信息中显示行号。
由于
答案 0 :(得分:1)
您可以检查异常的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
偏移为一个简单的表达式。