Search code examples
pythonprologffiswi-prolog

Is there any way to print it in python(python bridging on prolog)?


I am trying to run the prolog queries from the python program by using pyswip. Suppose i have a program like this,

from pyswip import Prolog
p = Prolog()
p.retractall('rule1(_,_)')
p.retractall('rule2(_,_)')
p.retractall('rule3(_,_)')
p.assertz('rule2(X):- writeln(\'in rule2\': X)')
p.assertz('rule1(X,Y):- rule2(X), writeln(\'rule2 exectued\'),rule3(Y)')
p.assertz('rule3(Y):- writeln(\'in rule3\': Y)')
print(list(p.query('rule1(1,2)')))

now what i want is that all those writeln rules which will print in prolog, i want that to be printed in the python terminal.is there any way to do it ?


Solution

  • For me this behaves as follows:

    >>> print(list(p.query('rule1(1,2)')))
    in rule2:1
    rule2 exectued
    in rule3:2
    [{}]
    

    Your writeln statements are executed as expected, the output is printed to the Python terminal. Is the output different for you? Do you want it to be different?

    Edit (see comments below): When Python is not run directly in a terminal but rather in a Jupyter notebook or similar, the Prolog output can get lost. In that case, the Prolog query can be wrapped in with_output_to(atom(PrologOutput), ...), which will capture the Prolog code's output in an atom (a Python string):

    >>> print(list(p.query('with_output_to(atom(PrologOutput), rule1(1,2))')))
    [{'PrologOutput': 'in rule2:1\nrule2 exectued\nin rule3:2\n'}]