4 library(janus): Call Python from Prolog
All Application Manual Name SummaryHelp

  • Documentation
    • Reference manual
    • Packages
      • SWI-Prolog Python interface
        • library(janus): Call Python from Prolog
          • py_version/0
          • py_call/1
          • py_call/2
          • py_call/3
          • py_iter/2
          • py_iter/3
          • py_setattr/3
          • py_is_object/1
          • py_is_dict/1
          • py_free/1
          • py_with_gil/1
          • py_gil_owner/1
          • py_func/3
          • py_func/4
          • py_dot/3
          • py_dot/4
          • values/3
          • keys/2
          • key/2
          • items/2
          • py_shell/0
          • py_pp/1
          • py_pp/2
          • py_pp/3
          • py_object_dir/2
          • py_object_dict/2
          • py_obj_dir/2
          • py_obj_dict/2
          • py_type/2
          • py_isinstance/2
          • py_module_exists/1
          • py_hasattr/2
          • py_import/2
          • py_module/2
          • py_initialize/3
          • py_lib_dirs/1
          • py_add_lib_dir/1
          • py_add_lib_dir/2
          • Handling Python errors in Prolog
          • Calling and data translation errors
          • Janus and virtual environments (venv)

4.1 Handling Python errors in Prolog

If py_call/2 or one of the other predicates that access Python causes Python to raise an exception, this exception is translated into a Prolog exception of the shape below. The library defines a rule for print_message/2 to render these errors in a human readable way.

error(python_error(ErrorType, Value), _)

Here, ErrorType is the name of the error type, as an atom, e.g., ’TypeError’. Value is the exception object represented by a Python object reference. The library(janus) defines the message formatting, which makes us end up with a message like below.

?- py_call(nomodule:noattr).
ERROR: Python 'ModuleNotFoundError':
ERROR:   No module named 'nomodule'
ERROR: In:
ERROR:   [10] janus:py_call(nomodule:noattr)

The Python stack trace is handed embedded into the second argument of the error(Formal, ImplementationDefined). If an exception is printed, printing the Python backtrace, is controlled by the Prolog flags py_backtrace (default true) and py_backtrace_depth (default 4).

Compatibility
PIP. The embedding of the Python backtrace is SWI-Prolog specific.