JuliaPy / pyjulia

python interface to julia
MIT License
886 stars 103 forks source link

report line number of julia exception #525

Open bernstei opened 1 year ago

bernstei commented 1 year ago

It would be very helpful if julia.Main.eval(str) reported the line number in the code string that raised the exception, as opposed to just repeating back the whole string. Is there any way to extract that information from the julia exception so it can be printed in julia.core.py::check_exception?

mkitti commented 1 year ago

We might be able to do it if we wrap the string in a begin ... end.

julia> Meta.parse("""
       begin
           println("Hello")
           error()
       end
       """) |> eval
Hello
ERROR: 
Stacktrace:
 [1] error()
   @ Base ./error.jl:44
 [2] top-level scope
   @ none:3
bernstei commented 1 year ago

Thanks. Let me see if that works in my use case, too.

bernstei commented 1 year ago

Just wrapping in begin/end isn't enough to modify the error message printed as part of the julia.core.JuliaError message, although I realize now that I'm not sure if you meant this to be the entire solution, or merely a part that'd make it easier to extract the line number.

What I've done for now is wrap my julia code snipped in a try/catch, with this catch block

catch e
    throw(error(string(e) * " in julia code location " * string(stacktrace(catch_backtrace()))))
end

This appends the julia code line to the error message, which is then printed by python as part of the JuliaError object. It does make the line number off by one, because of the try line, so it can't trivially be done as part of the julia python package, unless you want to edit the string returned by the JuliaError object to modify the line number, which would be a pretty ugly solution.