[python-nl] Decorator
Schneider
f.schneider at de-bleek.demon.nl
Mon May 14 11:25:27 CEST 2012
Dames, heren,
Omdat ik weinig ervaring met decorators en multiprocessing heb, ben ik
opzoek naar een beetje hulp.
Ik maak gebruik van CLIPS via PyClips (http://pyclips.sourceforge.net/)
waarbij CLIPS in een apart proces gestart wordt i.v.m. performance e.d. Om
Python aan te kunnen roepen vanuit CLIPS, moeten de Python functies in CLIPS
worden geregistreerd.
Meest basale vorm zonder decorators.
import clips
import multiprocessing
class CLIPS(object):
def __init__(self, data):
self.environment = clips.Environment()
self.data = data
clips.RegisterPythonFunction(self.pyprint, "pyprint")
self.environment.Load("test.clp")
self.environment.Reset()
self.environment.Run()
def pyprint(self, value):
print self.data, "".join(map(str, value))
class CLIPSProcess(multiprocessing.Process):
def run(self):
p = multiprocessing.current_process()
self.c = CLIPS("%s %s" % (p.name, p.pid))
pass
if __name__ == "__main__":
cp = CLIPSProcess()
cp.start()
Inhoud van test.clp is:
(defrule MAIN::start-me-up
=>
(python-call pyprint "Hello world")
)
Output is CLIPSProcess-1 2456 Hello world
Werkt goed. Nu wil ik heel wat "pyprint" achtige functies kunnen registreren
via iets als:
@clips_callable
def pyprint(self, value):
.
zonder dat ik steeds clips.RegisterPythonFunction hoef aan te roepen. Een
simpele decorator zoals hieronder werkt niet:
import clips
import multiprocessing
def clips_callable(f):
from functools import wraps
@wraps(f)
def wf(*args, **kwargs):
print 'calling {}'.format(f.__name__)
return f(*args, **kwargs)
clips.RegisterPythonFunction(wf, f.__name__)
return wf
class CLIPS(object):
def __init__(self, data):
self.environment = clips.Environment()
self.data = data
#clips.RegisterPythonFunction(self.pyprint, "pyprint")
self.environment.Load("test.clp")
self.environment.Reset()
self.environment.Run()
@clips_callable
def pyprint(self, value):
print self.data, "".join(map(str, value))
class CLIPSProcess(multiprocessing.Process):
def run(self):
p = multiprocessing.current_process()
self.c = CLIPS("%s %s" % (p.name, p.pid))
pass
if __name__ == "__main__":
cp = CLIPSProcess()
cp.start()
Met als output
calling pyprint
De decorator doet duidelijk niet wat ik wil. Heeft iemand misschien een
oplossing?
Met vriendelijke groet,
Frans
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-nl/attachments/20120514/78fc7b2a/attachment-0001.html>
More information about the Python-nl
mailing list