当使用IronPython并以C#/.NET为主机时,如何在运行时出错时得到有问题的行?

2024-10-01 11:21:03 发布

您现在位置:Python中文网/ 问答频道 /正文

被标题搞糊涂了?让我解释一下: 我确实在.NET进程(我的C应用程序是主机)中使用IronPython执行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冒泡。我能抓住这个,然后得到信息。
但是如何获取导致异常的脚本行或行号?


Tags: thein脚本应用程序标题net进程script
2条回答

你可以打电话来PythonOps.GetDynamicStackFrames并从DynamicStackFrame对象获取行号。在

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

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

相关问题 更多 >