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?
You can can call PythonOps.GetDynamicStackFrames on the exception and get the line numbers from the DynamicStackFrame objects.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With