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冒泡.我可以抓住这个,并得到消息.
但是如何获取导致异常的脚本行或行号?
您可以在异常上调用PythonOps.GetDynamicStackFrames并从DynamicStackFrame对象中获取行号.
这个答案提供了一种方法,可以将从IronPython代码中捕获的异常格式化为包含更多有用信息的字符串,例如行号和Python调用堆栈:
engine.GetService<ExceptionOperations>().FormatException(exception);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1883 次 |
| 最近记录: |