Search code examples
pythonclipsexpert-systempyclips

How to get a rule activation to call a python function, using PyClips


I am experimenting with PyClips and I want to integrate it tightly with Python, so that when a rule is activated, it calls a python function.

Here is what I have so far:

import clips

def addf(a, b):
    return a + b

clips.RegisterPythonFunction(addf)

clips.Build("""
(defrule duck
  (animal-is duck)
  =>
  (assert (sound-is quack))
  (printout t "it’s a duck" crlf))
  (python-call addf 40 2 )
""")

However, when I assert the fact 'animal-is duck', my python function is NOT being called:

>>> clips.Assert("(animal-is duck)")
<Fact 'f-0': fact object at 0x7fe4cb323720>
>>> clips.Run()
0

What am I doing wrong?


Solution

  • There's a misplaced bracket that closes the rule too soon leaving out the python-call:

    clips.Build("""
    (defrule duck
      (animal-is duck)
      =>
      (assert (sound-is quack))
      (printout t "it's a duck" crlf))
      (python-call addf 40 2 )       ^
    """)                      ^      |
                              |   this one
                              |
                          should go here
    

    If you want to verify that the addf actually returned 42, the result could be binded and printed it out:

    clips.Build("""
    (defrule duck
      (animal-is duck)
      =>
      (assert (sound-is quack))
      (printout t \"it's a duck\" crlf)
      (bind ?tot (python-call addf 40 2 ))
      (printout t ?tot crlf))
    """)
    
    
    clips.Assert("(animal-is duck)")
    clips.Run()
    t = clips.StdoutStream.Read()
    print t