Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the offending line when using IronPython with C#/.NET as host, on a runtime error?

Confused by the title? Let me explain: I do execute a python script, within a .NET process (my C# application being the host), using IronPython:

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);

The code shown above is running in a background thread (using the Task class). The script contains an error, which causes an IronPython.Runtime.Exceptionis.TypeErrorException to bubble up. I can catch this, and get the message.
But how to get the script line or line number that causes the exception?

like image 444
Marcel Avatar asked Jun 24 '11 13:06

Marcel


2 Answers

You can can call PythonOps.GetDynamicStackFrames on the exception and get the line numbers from the DynamicStackFrame objects.

like image 160
Dino Viehland Avatar answered Sep 21 '22 10:09

Dino Viehland


This answer provides a means to format an exception caught from IronPython code into a string that contains more useful information such as line numbers and the Python call stack:

engine.GetService<ExceptionOperations>().FormatException(exception);
like image 31
Drew Noakes Avatar answered Sep 20 '22 10:09

Drew Noakes