Call prolog predicate from python

I have a file .pland I want to call the predicate declared in it from a python script. How can i do this?

For instance, test.pl

rD( [], Ans, Ans ).
rD( [X|Xs], Ans, Acc ) :-
    member( X, Acc ),
    rD( Xs, Ans, Acc ), !.
rD( [X|Xs], Ans, Acc ) :-
    \+member( X, Acc ),
    append( Acc, [X], AccNew ),
    rD( Xs, Ans, AccNew ), !.

Works like

?- rD( [1,2,3,4,5,4], X ).
X = [1, 2, 3, 4, 5].

I want to somehow call rDfrom a python script and get the answer in the result variable

result
[1, 2, 3, 4, 5]

ps: this is just an example, and I don't want to rewrite the current Prolog program.

+4
source share
4 answers

, PySWIP, Python SWI-Prolog. , Google Code, .

(5 2019 .)

PySWIP Github . TL;DR: SWI-Prolog pip install pyswip Python 2, 3.

+3

" Prolog", , Python SWI-Prolog, .

SO < Python 2008 . subprocess, stdout , Python .

SWI-Prolog. SWI-Prolog script Unix- DOS//cmd Windows, .

. . 2.4.2 SWI-Prolog (. ) -g -t. :

swipl --quiet -t rD( [1,2,3,4,5,4], X ),halt

, . --quiet /, , , , Python.

+2

The update for Python3, PySwip in PyPI at the time of writing, is only for legacy Python, but the source code on github is compatible with Python3. You can git clone this, run python3 setup.py installand it will give you a version of Python3.

To access the existing knowledge base stored as Knowledge_base.pl:

from pyswip import Prolog
prolog = Prolog()
prolog.consult("knowledge_base.pl")
for res in prolog.query("rD( [1,2,3,4,5,4], X )."):
    print(res)

# output:
# {'X': [1, 2, 3, 4, 5]}
+1
source
from subprocess import Popen, PIPE, STDOUT

p = Popen('/usr/local/sicstus4.2.3/bin/sicstus', shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT)
cmd = open('/path/to/your/test.pl').read()
res = p.communicate(cmd)
for line in res:
    print line
0
source

All Articles