在运行时出错的情况下,当使用IronPython和C#/.NET作为主机时,如何获得有问题的行?

在运行时出错的情况下,当使用IronPython和C#/.NET作为主机时,如何获得有问题的行?,.net,python,exception,runtime,.net,Python,Exception,Runtime,被标题搞糊涂了?让我解释一下: 我确实使用IronPython在.NET进程(我的C#应用程序是主机)内执行python脚本: ScriptEngine python = Python.CreateEngine(); ScriptSource pyFromFileSource = python.CreateScriptSourceFromString(script); CompiledCode pyFromFileCode = pyFromFileSource.Compile(); Script

被标题搞糊涂了?让我解释一下: 我确实使用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);
上面显示的代码在后台线程中运行(使用
Task
类)。该脚本包含一个错误,导致出现
IronPython.Runtime.Exceptionis.TypeErrorException
。我能抓住这个,并得到信息。

但是如何获取导致异常的脚本行或行号?

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

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

engine.GetService<ExceptionOperations>().FormatException(exception);
engine.GetService().FormatException(异常);

感谢您提供此解决方案。效果很好!很好,谢谢。对于任何正在寻找它的人,
PythonOps
位于
IronPython.Runtime.Operations
中。