Getting Prolog running inside Python
So that you can follow the code snippets, I will show you how to embed Prolog in Python in the least painful way.
Prolog is not hard to implement by hand, at least not the most common parts: logic resolution and arithmetic constraints. But that won’t get you the full power of Prolog, and will probably have a few bugs :)
So, there are a lot of different Prolog interpreters and compilers out there. There are GNU Prolog, CIAO Prolog, SICStus and SWI Prolog. Out of those, SWI Prolog has a good website with great documentation and a working Python bridge.
To start, install the library PySwip. Since I use uv to manage my dependencies, I run it like this:
uv add pyswipAnd you must also install some version of SWI Prolog. There are installers for different operating systems and you will find them at the SWI Prolog download page.
Personally, I did it with homebrew, via:
brew install swiplNow, in order to PySwip to find your SWI Prolog installation, it looks at two environment variables: LIBSWIPL_PATH and SWI_HOME_DIR.
Find them via:
swipl --dump-runtime-variables It will dump the environment variables from SWI Prolog, and you will look at the following lines:
PLBASE="/opt/homebrew/Cellar/swi-prolog/9.2.9/lib/swipl";
SWIPL_PACK_PATH="";
PLARCH="arm64-darwin";
PLBITS="64";
PLVERSION="90209";
PLSOEXT="so";
PLSOPATH="DYLD_LIBRARY_PATH";
PLLIBDIR="/opt/homebrew/Cellar/swi-prolog/9.2.9/lib/swipl/lib/arm64-darwin";
PLLIB="-lswipl";
PLLIBSWIPL="/opt/homebrew/Cellar/swi-prolog/9.2.9/lib/swipl/lib/arm64-darwin/libswipl.9.2.9.dylib";
PLSHARED="yes";
PLTHREADS="yes";Now, create a new file, and:
LIBSWIPL_PATHmaps toPLLIBSWIPLSWI_HOME_DIRmaps toPLBASE
Add those to a .env file. Then, before importing Prolog, ensure you have loaded it, (assuming you installed python-dotenv):
import dotenv
dotenv.load_env()
from pyswip import Prolog
prolog = Prolog()And in order to communicate with Prolog, use consult to load a file, assert and query:
prolog.assertz("edge(a,b)")
prolog.assertz("edge(a,c)")
prolog.assertz("edge(c,d)")
prolog.assertz("path(X,Y) :- edge(X,Y)")
prolog.assertz("path(X,Y) :- edge(X,Z), path(Z, Y)")
# Get all points reachable from a.
print(prolog.query("path(a, X)"))So this can start you playing with Prolog from inside Python, where you can glue it to other tech you like.


