How to get a violation string when using IronPython with C # /. NET as a host with a runtime error?

Confused by the name? Let me explain: I am running a python script in a .NET process (my C # application is 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 runs in the background thread (using the Task class). The script contains an error causing the IronPython.Runtime.Exceptionis.TypeErrorException bubble. I can catch this and get a message.
But how to get the line or line number of the script that throws the exception?

+7
source share
2 answers

You can call PythonOps.GetDynamicStackFrames to exclude and get line numbers from DynamicStackFrame objects.

+8
source

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

 engine.GetService<ExceptionOperations>().FormatException(exception); 
+5
source

All Articles