Using Python Functions From the Clips Expert System

吃可爱长大的小学妹 提交于 2019-12-03 08:27:26

I received some help on the PyClips support group. The solution is to ensure your Python function returns a clips.Symbol object and use (test ...) to evaluate functions in the LHS of rules. The use of Reset() also appears to be necessary to activate certain rules.

import clips
clips.Reset()

user = True

def py_getvar(k):
    return (clips.Symbol('TRUE') if globals().get(k) else clips.Symbol('FALSE'))

clips.RegisterPythonFunction(py_getvar)

# if globals().get('user') is not None: assert something
clips.BuildRule("user-rule", "(test (eq (python-call py_getvar user) TRUE))",
                '(assert (user-present))',
                "the user rule")

clips.Run()
clips.PrintFacts()

Your problem has something to do with the (neq (python-call py_getvar user) 'None'). Apparently clips doesn't like the nested statement. It appears that trying to wrap a function call in an equality statement does bad things. However you'll never assert the value anyway as your function returns either Nil or the value. Instead what you'll want to do is this:

def py_getvar(k):
    return clips.Symbol('TRUE') if globals.get(k) else clips.Symbol('FALSE')

then just change "(neq (python-call py_getvar user) 'None')" to "(python-call py_getvar user)"

And that should work. Haven't used pyclips before messing with it just now, but that should do what you want.

HTH!

>>> import clips
>>> def py_getvar(k):
...     return clips.Symbol('TRUE') if globals.get(k) else clips.Symbol('FALSE')

...
>>> clips.RegisterPythonFunction(py_getvar)
>>> clips.BuildRule("user-rule", "(python-call py_getvar user)", "(assert (user-
present))", "the user rule")
<Rule 'user-rule': defrule object at 0x00A691D0>
>>> clips.Run()
0
>>> clips.PrintFacts()
>>>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!