如何在运行时错误的情况下使用IronPython与C#/ .NET作为主机时获取违规行?

Mar*_*cel 8 .net python runtime exception

被标题混淆了?让我解释一下:我使用IronPython在.NET进程(我的C#应用​​程序是主机)中执行python脚本:

ScriptEngine python = Python.CreateEngine();
ScriptSource pyFromFileSource = python.CreateScriptSourceFromString(script);
CompiledCode pyFromFileCode = pyFromFileSource.Compile();
ScriptRuntime runtime = engine.Runtime;
ScriptScope scope = runtime.CreateScope(); //get a scope where we put in the stuff from the host
scope.SetVariable("lab", this); //allow usage of this class in the script
script.Execute(scope);
Run Code Online (Sandbox Code Playgroud)

上面显示的代码在后台线程中运行(使用Task该类).该脚本包含一个错误,导致IronPython.Runtime.Exceptionis.TypeErrorException冒泡.我可以抓住这个,并得到消息.
但是如何获取导致异常的脚本行或行号?

Din*_*and 9

您可以在异常上调用PythonOps.GetDynamicStackFrames并从DynamicStackFrame对象中获取行号.

  • 工作得很好,谢谢.对于其他寻找它的人来说,`PythonOps`位于`IronPython.Runtime.Operations`中. (3认同)

Dre*_*kes 5

这个答案提供了一种方法,可以将从IronPython代码中捕获的异常格式化为包含更多有用信息的字符串,例如行号和Python调用堆栈:

engine.GetService<ExceptionOperations>().FormatException(exception);
Run Code Online (Sandbox Code Playgroud)